gpt4 book ai didi

javascript - 为什么访问API时需要在请求头中添加 `Authorization`?

转载 作者:行者123 更新时间:2023-12-03 02:17:44 25 4
gpt4 key购买 nike

我使用Python/Django编写后端,使用Django-Rest-Framework编写API,我还使用了rest_authallauth,请参阅我的设置.py:

INSTALLED_APPS = [
...

'corsheaders',

'rest_framework',
'rest_framework.authtoken',
'rest_framework_docs', # API docs
'rest_auth',
'allauth',
'allauth.account',

但前端访问API时,必须在Authorization中添加Authorization请求Header,否则无法访问成功:举个例子:

    var that = this

// login
that.$http.post(Urls.users.login(), params).then((response) => {

that.$Cookies.set('token', response.data.key);

}).catch((response) => { // if the header do not have `Authorization`, there will go to there directly, and pay attention: the response is undefined.


}
)

最佳答案

您将'rest_framework.authtoken'添加到INSTALLED_APPS并设置

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticatedOrReadOnly',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}

在settings.py中。然后,当您使用 post\patch\delete 等不安全方法询问服务器时,DjangoRestFramework 将检查您的身份。您的 login 方法由 处理post 方法会询问身份。但是您在登录后会获得您的 token

有两种方法来解决您的问题,其中一种是设置的:

'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),

不推荐。第二种方法是为您的登录方法设置权限,例如:

from rest_framework.permissions import AllowAny
@list_route(methods=['POST'], permission_classes=[AllowAny])
def login(self, request):
pass

关于javascript - 为什么访问API时需要在请求头中添加 `Authorization`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49294383/

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