【问题标题】:Why I need add the `Authorization` in the request header when access the APIs?为什么在访问 API 时需要在请求头中添加“授权”?
【发布时间】:2018-03-15 08:14:35
【问题描述】:

我用Python/Django写后端,用Django-Rest-Framework写API,我也用rest_authallauth,看我的settings.py

INSTALLED_APPS = [
    ...

    'corsheaders', 

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

但是当前端访问API时,它必须添加Authorization在 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.


      }
    )

【问题讨论】:

    标签: javascript python django-allauth django-rest-auth


    【解决方案1】:

    您将'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 方法处理,该方法将询问身份。但是您在login 之后得到您的token

    两种方式来处理你的问题,一种是设置:

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

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

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

    【讨论】:

    • rest_auth 是否是 rest_framework 的一部分(django-rest-framework 的一部分)?
    • 不,它是第 3 方应用程序。
    猜你喜欢
    • 2019-06-06
    • 2016-03-27
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 2014-12-28
    • 2020-03-07
    • 1970-01-01
    • 2014-07-22
    相关资源
    最近更新 更多