我正在使用 Django 2.x 和 Django REST 框架。
我django-oauth-toolkit
用于启用OAuth2
身份验证、django-rest-auth
登录和django-allauth
用户注册。
当用户成功注册时,我想在响应中生成访问令牌。为此,我正在使用自定义注册视图。
为此,我创建了一个函数 utils
def generate_token(request, user):
# Get OAuth application to use
application_: Application = Application.objects.filter(
client_type=Application.CLIENT_CONFIDENTIAL,
authorization_grant_type=Application.GRANT_PASSWORD
).first()
if not application_:
raise Exception('No OAuth2 Application is setup')
auth_data = {
'username': user.username,
'password': password,
'grant_type': 'password',
'client_id': application_.client_id,
'client_secret': application_.client_secret
}
if request.data:
mutable = request.data._mutable
request.data._mutable = True
request.data.update(auth_data)
request.data._mutable = mutable
if request.POST:
mutable = request.POST._mutable
request.POST._mutable = True
request.POST.update(auth_data)
request.POST._mutable = mutable
return TokenView().create_token_response(request=request)
当端点被邮递员击中时,它工作正常并且request.data
具有_mutable
属性。
但是当它被 Angular 应用程序击中时,它会给出错误
'dict' object has no attribute '_mutable'
并且错误指向mutable = request.data._mutable
为什么_mutable
缺少某些请求?
编辑 2:请求标头
Postman发送的请求头是
Content-Type:"application/json"
Accept:"application/json, text/plain, /"
User-Agent:"PostmanRuntime/7.15.2"
Cache-Control:"no-cache"
Postman-Token:"b4461728-a6a9-48da-a4fa-3894920b5484"
Host:"api.staging.scanova.io"
Cookie:"messages="660481c3ce8c48b1884641ffdec0a3f701cdc9cf$..."; csrftoken=tNa6o6RDkEUTBti1cDJCvgV5oLG84qczgADeDfSY7hROsLP6cmhIgQKaamPQU7Xy; sessionid=r0l8kh58n8i14quyemj60ur6i59uhy1i"
Accept-Encoding:"gzip, deflate"
Content-Length:635
Connection:"keep-alive"
来自 Angular 的请求标头是
Accept: application/json, text/plain, */*
Authorization: false false
Content-Type: application/json
Origin: https://localhost:4200
Referer: https://localhost:4200/auth/register
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36
编辑 3:请求类型
从端点调用的主视图是CreateAPIView
. generate_token
从此视图调用,TokenView
用于生成访问令牌。使用TokenView
Django 的通用View
.