python - 为什么我的请求会话将数据视图丢失到 auth azure AD 中的另一个视图?
问题描述
我正在尝试将我的 django 平台与 azure 广告身份验证集成,因此我遵循了以下文档 https://docs.microsoft.com/pt-br/graph/tutorials/python。
在我的项目中,我只能在 AD 登录完成并正常工作时登录到我的平台用户,所以我试图通过会话将用户传递给回调视图(一旦 AD 登录完成就会调用它) ,有时它有效,但大多数时候会话完全是空的
def sign_in_ad(request, pk):
request.session.flush()
# Get the sign-in URL
user = User.objects.filter(id=pk).first()
company_azure = CompanyAzureAd.objects.filter(company=user.employee.firm).first()
sign_in_url, state = get_sign_in_url(company_azure)
# Save the expected state so we can validate in the callback
request.session.update({'user_id': pk})
request.session.update({'auth_state': state})
request.session.modified = True
# Redirect to the Azure sign-in page
return HttpResponseRedirect(sign_in_url)
def callback(request):
user_id = request.session['user_id'] #Error key not exist
user_platform = User.objects.filter(id=int(user_id)).first()
company_azure = CompanyAzureAd.objects.filter(company=user_platform.employee.firm).first()
# Get the state saved in session
expected_state = ''
# Make the token request
url = request.build_absolute_uri(request.get_full_path())
if "http:" in url:
url = "https:" + url[5:]
token = get_token_from_code(url, expected_state, company_azure)
# Get the user's profile
user = get_user(token)
# Save token and user
store_token(request, token)
store_user(request, user)
login(request, user_platform, backend='django.contrib.auth.backends.ModelBackend')
return HttpResponseRedirect(reverse('dashboard'))
我不明白为什么会话是空的,有更好的方法来执行这个集成,我需要用户先登录我的平台,然后重定向到 AD,这个流程有效,问题在最后一部分,在平台上救援用户并对其进行身份验证时
这是我的 get_sign_url:
def get_sign_in_url(company_azure):
company_azure = json.loads(company_azure.keys)
authority = company_azure['authority']
authorize_url = f'https://login.microsoftonline.com/{authority}/oauth2/v2.0/authorize'
# Initialize the OAuth client
aad_auth = OAuth2Session(
company_azure['app_id'],
scope='User.Read email Calendars.Read openid profile',
redirect_uri='http://localhost:8000/tutorial/callback'
)
sign_in_url, state = aad_auth.authorization_url(authorize_url, prompt='login')
return sign_in_url, state
解决方案
推荐阅读
- postgresql - 使用 psql 脚本将 jsonb 逗号分隔值转换为 json 对象
- scala - 从 Scala 中的元组列表创建数据框
- jquery - 我想从 API 中获取某些结果并将其显示到我的页面上
- react-native - 在 React Native Paper 中更改 TextInput 的文本颜色
- typescript - 设置 mat-option 值反应形式
- vue.js - 在整个 Vue 组件中使用变量?
- google-apps-script - 如何根据 Google AppMaker 中的表格字段填充下拉列表
- html - 使用 Flex Box 在盒子中组织材料 HTML CSS
- c++ - Boost Graph Library 不能存储对其他顶点的引用?
- c - 如何将`int`数组转换为C中的IP地址字符串?