Django Rest框架设置允许Flutter使用认证密钥进行认证

lsmd5eda  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(104)

我在前端使用flutter,在后台使用Django,并尝试获取用户详细信息,登录工作正常,返回令牌密钥
我不断得到未经授权或禁止的错误,并更新了几次标题。

final response = await http.get(
    url,
    headers: {
      HttpHeaders.authorizationHeader:
          'Authorization: Bearer ......bla bla ..........',
          //'Bearer ......bla bla bla ...',
    },
  );

但我一直得到{detail: Authentication credentials were not provided.},从Django Rest Framework终端它显示:Forbidden: /api/dj-rest-auth/user/
这里是Django settings.py:

INSTALLED_APPS = [
.......................
    'rest_framework',
    'users',
    'corsheaders',
    'django.contrib.sites',
    'rest_framework.authtoken',
    'dj_rest_auth',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'dj_rest_auth.registration',
]

# REST_FRAMEWORK = {
#     'DEFAULT_PERMISSION_CLASSES': [
#     'rest_framework.permissions.AllowAny',
#
# ]}
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

CORS_ALLOW_ALL_ORIGINS=True
AllowAny =True

当我尝试使用'rest_framework.permissions.AllowAny'
使用时返回禁止
'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework.authentication.TokenAuthentication',), 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',)
已退回未经授权
这里是views.py:

@csrf_exempt
def aPage(request):
    user:User=User.objects.get(pk=1)
    username=request.POST.get("username")
    email=request.POST.get("email")
    print(email)
    print(username)
    return JsonResponse({"Username":username , "email": email})

我如何发送认证登录用户使用他们的令牌,让他们从api获取数据?我做错了什么,返回这些错误?

mccptt67

mccptt671#

HttpHeaders.authorizationHeader的值为**“authorization”**,因为它正在发送无效的标头。请尝试如下所示

headers: {
      HttpHeaders.authorizationHeader: 'Bearer xxxxxxxx',
},

相关问题