Azure AD 重定向 URI 从 https 更改为 http

And*_*sch 3 authentication django oauth-2.0 azure-active-directory azure-ad-msal

概述

我在 Azure AD 门户注册了一个应用程序。重定向机制在开发过程中一直运行良好,但 Oauth 重定向 URI 上发生了奇怪的转换。

客户端应用程序是使用 Django 框架并使用 MSAL for Python 库构建的。

问题具体

假设我在 Azure AD 应用程序注册中指定了重定向 URI,如下所示:https://myapp.com/auth/redirect

我收到一个错误AADSTS50011: The reply URL specified in the request does not match the reply URLs configured for the application: '<application ID>'

深入研究发送的请求,我可以看到重定向 URI 在该过程中的某个地方以某种方式被操纵。
(注意https -> http的转换
...redirect_uri=http%3A%2F%2Fmyapp.com%2Fauth%2Fredirect&scope=User.Read.basic....

但 Azure AD 实际上甚至不接受纯 http 的 URL。

我尝试仅使用 localhost 产生相同的错误(因为 localhost URL 是规则的例外,只允许 https URL),并且使用重定向 URL,http://localhost:8000/auth/redirect身份验证过程可以正常工作,并https://localhost:8000/auth/redirect产生与上述相同的结果。

And*_*sch 7

实际问题出来了...

该错误更多地与 Django 内部结构与 MSAL 库的结合有关。

适用于 Python 的Azure AD MSAL 库在内部使用reverse(redirect_uri)方法在内部某处构建重定向 uri,并且由于 Django 请求在内部使用 HTTP,因此添加到请求中的重定向 uri 是 HTTP 的。

解决方案

添加SECURE_SSL_REDIRECT = Truesettings.py解决问题。

虽然普通./manage.py runserver命令不支持HTTPS,所以

  1. pip install werkzeug django-extensions pyOpenSSL
  2. django_extensions在setting.py下添加INSTALLED_APPS
  3. 运行服务器./manage.py runserver_plus --cert /tmp/cert localhost:8000

当程序在具有前端代理的 Web 服务器中运行时,也添加此行,以免更改后端返回的原始请求:
在 settings.py ->SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')