Javascript 为什么在访问API时需要在请求头中添加“Authorization”?
我使用Python/Django编写后端,使用Django Rest框架编写API,我还使用了Javascript 为什么在访问API时需要在请求头中添加“Authorization”?,javascript,python,django-allauth,django-rest-auth,Javascript,Python,Django Allauth,Django Rest Auth,我使用Python/Django编写后端,使用Django Rest框架编写API,我还使用了Rest\u auth,allauth,请参见我的settings.py: INSTALLED_APPS = [ ... 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_docs', # API docs 'rest_auth', 'a
Rest\u auth
,allauth
,请参见我的settings.py
:
INSTALLED_APPS = [
...
'corsheaders',
'rest_framework',
'rest_framework.authtoken',
'rest_framework_docs', # API docs
'rest_auth',
'allauth',
'allauth.account',
但是当前端访问API时,它必须在
请求标头,否则无法访问成功:
例如:
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\u framework.authtoken'
添加到已安装的应用程序中
并设置
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticatedOrReadOnly',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}
在settings.py中。
然后,当您使用不安全的方法(如post\patch\delete
)询问服务器时,DjangoRestFramework
将检查您的身份。您的login
方法由post
方法处理,该方法将询问身份。但您在登录后获得令牌
有两种方法可以解决您的问题,一种是:
'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
rest\u auth
是否是rest\u框架的一部分(django rest框架的一部分)?否,它是第三方应用程序。