gpt4 book ai didi

python - Azure B2C : Error in the callback after the edit profile when it tries to get a new token

转载 作者:行者123 更新时间:2023-12-03 03:35:18 28 4
gpt4 key购买 nike

我尝试在 Django 中实现 azure B2C 身份验证。

不幸的是,Django 中关于这个主题的文档并不多。不过,我设法编写了函数和 View 来获取 id_token 并将用户信息存储在 session 中。

我想在用户经过身份验证后将编辑配置文件与特定权限集成。页面完美重定向以更新用户信息。但是,在验证新数据后,当我尝试获取新 token (函数_get_token_from_code)时,我在回调中收到一条错误消息。

{'error': 'invalid_grant', 'error_description': 'AADB2C90088: The provided grant has not been issued for this endpoint. Actual Value : B2C_1_signupsignin_20220810 and Expected Value : B2C_1_profileediting\r\nCorrelation ID: xxxxxxxxxxx nTimestamp: 2022-08-31 14:58:54Z\r\n'}

因此这意味着 python 执行中出现以下错误:

 _store_user(request, result['id_token_claims'])
KeyError: 'id_token_claims'

但是用户的新信息正确保存在azure中。

由于我是此身份验证过程中的新手?我们是否需要为编辑个人资料用户流程生成新 token ?这个错误从何而来?

这是 djnago 中的代码:

load_dotenv()

def initialize_context(request):
context = {}

# Check for any errors in the session
error = request.session.pop('flash_error', None)

if error != None:
context['errors'] = []
context['errors'].append(error)

# Check for user in the session
context['user'] = request.session.get('user', {'is_authenticated': False})

return context

def index(request) :

context = initialize_context(request)

return render(request, 'index.html', context)

def sign_in(request) :

flow = _build_auth_code_flow()

try:
request.session['auth_flow'] = flow
except Exception as e:
print(e)
return HttpResponseRedirect(flow['auth_uri'])

def callback(request) :

result = _get_token_from_code(request)
print(result)

# Store user from auth_helper.py script
_store_user(request, result['id_token_claims'])
return redirect('home')

def home(request) :

context = initialize_context(request)
context['edit'] = os.getenv("B2C_PROFILE_AUTHORITY")
context['user'] = request.session['user'].get('emails')[0]

return render(request, 'home.html', context)

def editprofile(request) :

authority = os.getenv("B2C_PROFILE_AUTHORITY")

flow = _build_auth_code_flow(authority=authority)

try:
request.session['auth_flow'] = flow
except Exception as e:
print(e)
return HttpResponseRedirect(flow['auth_uri'])




#----- Library -----------------------

def _build_msal_app(cache=None, authority=None):

auth_app = msal.ConfidentialClientApplication(
os.getenv("CLIENT_ID"),
authority=authority or os.getenv("AUTHORITY"),
client_credential=os.getenv("CLIENT_SECRET"),
token_cache=cache)
return auth_app

def _build_auth_code_flow(authority=None, scopes=None):

return _build_msal_app(authority=authority).initiate_auth_code_flow(
scopes or [],
redirect_uri="http://localhost:8000/getAToken")

def _get_token_from_code(request):

cache = _load_cache(request)
auth_app = _build_msal_app(cache)

# Get the flow saved in session
flow = request.session.pop('auth_flow', {})

result = auth_app.acquire_token_by_auth_code_flow(flow, request.GET)
_save_cache(request, cache)

return result

def _load_cache(request):
# Check for a token cache in the session
cache = msal.SerializableTokenCache()
if request.session.get('token_cache'):
cache.deserialize(request.session['token_cache'])

return cache

def _save_cache(request, cache):
# If cache has changed, persist back to session
if cache.has_state_changed:
request.session['token_cache'] = cache.serialize()

def _store_user(request, user):
try:
request.session['user'] = {
'is_authenticated': True,
'name': user['given_name'],
'emails': user['emails'] if (user['emails'] != None) else user['userPrincipalName'],
# 'timeZone': user['mailboxSettings']['timeZone'] if (user['mailboxSettings']['timeZone'] != None) else 'UTC'
}

except Exception as e:
print(e)

最佳答案

这是一个使用 https://django-allauth.readthedocs.io/en/latest/ 的解决方案我们在多个项目中使用这个库来通过 MS Azure/Graph 和其他提供商进行身份验证。它为很多身份提供商平台提供适配器。

  1. 添加到 INSTALLED_APPS:
    'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.microsoft',
  • 您的 django-allauth 设置需要包括:
  • SOCIALACCOUNT_PROVIDERS = {
    'microsoft': {
    'tenant': 'XXX', # replace this with your tenant name, see Azure
    'SCOPE': ['User.Read', 'openid', 'email', 'profile'],
    }
    }
  • 由于您可能有自定义登录表单,因此您需要将 django-allauth 的登录功能添加到其中。这是一个示例,请参阅 django-allauth 文档以获取解释。
  • {% load i18n static socialaccount %}
    {% for provider in socialaccount_providers %}
    <p>
    <a href="{% provider_login_url provider.id process='login' scope=scope auth_params=auth_params %}">
    {% trans "Log in with" %}
    <strong>{{ provider.name}}</strong>
    </a>
    </p>
    {% endfor %}

    django-allauth 将在自己的模型中存储 token 。您可以像这样访问用户的 token :

    from allauth.socialaccount.models import SocialToken

    social_token = SocialToken.objects.filter(
    account__user=request.user, account__provider='microsoft'
    ).order_by('-expires_at').first()
    if social_token and social_token.token:
    # social_token.token is the OAuth2 access_token

    关于python - Azure B2C : Error in the callback after the edit profile when it tries to get a new token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73558031/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com