为什么访问API时需要在请求头中添加`Authorization`?
Why I need add the `Authorization` in the request header when access the APIs?
我用Python/Django写后端,用Django-Rest-Framework写API,我也用过rest_auth
,allauth
,看我的settings.py
:
INSTALLED_APPS = [
...
'corsheaders',
'rest_framework',
'rest_framework.authtoken',
'rest_framework_docs', # API docs
'rest_auth',
'allauth',
'allauth.account',
但是前端访问API时,必须在
Request 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 中。
然后 DjangoRestFramework
将在您使用 post\patch\delete
等不安全方法询问服务器时检查您的身份。您 login
方法由 post
方法处理,该方法将询问 identity.But 您得到你的 token
在 login
.
之后
两种方法来解决你的问题,一种是设置:
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
这不是 recommend.second 方式是为您的 login
方法设置权限,例如:
from rest_framework.permissions import AllowAny
@list_route(methods=['POST'], permission_classes=[AllowAny])
def login(self, request):
pass
我用Python/Django写后端,用Django-Rest-Framework写API,我也用过rest_auth
,allauth
,看我的settings.py
:
INSTALLED_APPS = [
...
'corsheaders',
'rest_framework',
'rest_framework.authtoken',
'rest_framework_docs', # API docs
'rest_auth',
'allauth',
'allauth.account',
但是前端访问API时,必须在 Request 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 中。
然后 DjangoRestFramework
将在您使用 post\patch\delete
等不安全方法询问服务器时检查您的身份。您 login
方法由 post
方法处理,该方法将询问 identity.But 您得到你的 token
在 login
.
两种方法来解决你的问题,一种是设置:
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
这不是 recommend.second 方式是为您的 login
方法设置权限,例如:
from rest_framework.permissions import AllowAny
@list_route(methods=['POST'], permission_classes=[AllowAny])
def login(self, request):
pass