MSAL:会话数据损坏 - redirect_uri 不匹配
我正在搭建一个自托管的Django网页应用,这个应用会使用一个叫做identity的库(这是一个MSAL的封装库),来获取OAuth令牌,以便访问我租户的资源(通过MSGraph API调用)。
我从这里下载了一个示例网页应用:https://github.com/Azure-Samples/ms-identity-python-webapp-django,并按照说明在我的AzureAD租户上授权了这个应用,使用的重定向URI是:
http://localhost:8080/redirect
Launching the app on my localhost I get the follwoing error:
Django version 5.0.3, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8080/
Quit the server with CONTROL-C.
Session data corrupted
redirect_uri mismatch: configured = http://localhost:8080/redirect, calculated = http://127.0.0.1:8080/redirect
[26/Mar/2024 10:53:19] "GET / HTTP/1.1" 200 715
我尝试把Azure AD上的URI改成:http://127.0.0.1:8080/redirect,但显然:

我尝试通过ngrok在AzureAD和我的本地服务器之间建立隧道。服务器正常响应,显示登录页面:

但是一加载页面,我就看到服务器日志里又出现了URI不匹配的问题:
Session data corrupted
redirect_uri mismatch: configured = https://6ae1-89-64-xx-xx.ngrok-free.app/redirect, calculated = http://6ae1-89-64-xx-xx.ngrok-free.app/redirect
[26/Mar/2024 10:34:47] "GET / HTTP/1.1" 200 730
Not Found: /favicon.ico
注意,上面的日志信息中,分配给'calculated'变量的URI丢失了's'!
在网页上,我仍然可以输入我的用户凭证,但却收到了这个错误页面:

Python版本是3.10.5,
包的版本如下:
Django==5.0.3
identity==0.6.0
msal==1.28.0
此时我有几个问题:
http://localhost:8080/redirect和http://127.0.0.1:8080/redirect不一样吗?这是个bug,还是我不知道的某种设计?
为什么MSAL会把我的重定向URI中的"s"去掉?
我该如何解决这个问题?
1 个回答
我使用了同样的GitHub代码,顺利地完成了登录和登出,没有遇到任何问题。
为了修复这个问题,我使用下面的命令来运行应用程序。
python manage.py runserver localhost:8000
.env :
POST_BUILD_COMMAND=python manage.py migrate
CLIENT_ID='<client_ID>'
AUTHORITY='https://<tenant_name>.b2clogin.com/<tenant_name>.onmicrosoft.com/<policy_name>'
REDIRECT_URI='http://localhost:8000/redirect'
SCOPE=User.ReadBasic.All
ENDPOINT=https://graph.microsoft.com/v1.0/users
SIGNUPSIGNIN_USER_FLOW='<policy_name>'
EDITPROFILE_USER_FLOW='<policy_name>'
RESETPASSWORD_USER_FLOW='<policy_name>'
我在Azure AD B2C的身份验证中添加了下面的URL,作为一个单页面应用,如下所示:
http://localhost:8000/redirect
输出 :
这个Django项目成功运行,结果如下:
C:\Users\xxxxxxxx\Downloads\ms-identity-python-webapp-django-main\ms-identity-python-webapp-django-main>python manage.py runserver localhost:8000
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
March 27, 2024 - 16:45:07
Django version 5.0.3, using settings 'mysite.settings'
Starting development server at http://localhost:8000/
Quit the server with CTRL-BREAK.
Session data corrupted
[27/Mar/2024 16:45:27] "GET / HTTP/1.1" 200 710
[27/Mar/2024 16:46:33] "GET /redirect?state=BErLfztOxxxxxxxxxxx&client_info=eyJ1aWQixxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx HTTP/1.1" 302 0
[27/Mar/2024 16:46:33] "GET / HTTP/1.1" 200 759
[27/Mar/2024 16:46:52] "GET /logout HTTP/1.1" 302 0
[27/Mar/2024 16:46:53] "GET / HTTP/1.1" 200 710
浏览器输出 :
我在上面的URL中得到了以下输出,并点击了登录按钮进行登录,如下所示:
这把我重定向到了下面的页面,我输入了我的B2C凭证进行登录,如下所示:
我成功登录后,得到了下面的页面。我点击了登出按钮进行登出,如下所示。