简体   繁体   中英

Why I need add the `Authorization` in the request header when access the APIs?

I use the Python/Django write the backend, use Django-Rest-Framework write the APIs, I also used the rest_auth , allauth , see my settings.py :

INSTALLED_APPS = [
    ...

    'corsheaders', 

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

but when the frontend access the APIs, it will must add the Authorization in the Request Header, otherwise can not access success: as a example:

    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.


      }
    )

You add 'rest_framework.authtoken' to INSTALLED_APPS and set

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

in settings.py. Then DjangoRestFramework will check you identity when you ask server with unsafe method like post\patch\delete .You login method is handle by post method which will ask identity.But you get your token after login .

Two way to handle you problem, one is set:

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

which is not recommend.second way is set permissions for your login method like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM