How to authorize django-rest-knox login path without 401 error?

后端 未结 3 809
予麋鹿
予麋鹿 2021-01-21 20:39

I\'m trying to put an authentication api on my django app so I can start using a Vue+Node frontend. I\'ve read over the knox documentation, but I don\'t seem to see anything su

相关标签:
3条回答
  • 2021-01-21 21:02

    I ended up getting it work by dropping knox and just using basic auth. I did make other changes like using rest_framework.authentication.TokenAuthentication and rest_framework.permissions.IsAuthenticated in my REST_FRAMEWORK setting and including permission_classes = (AllowAny, ) in my registration and login APIViews. Pretty basic stuff, but I think this should work for what I need. I don't know what I was doing wrong with knox but it seems more trouble that it is worth.

    0 讨论(0)
  • 2021-01-21 21:05

    Short answer, go to settings.py and edit DEFAULT_AUTHENTICATION_CLASSES :

    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
             'rest_framework.authentication.BasicAuthentication' ,
             'knox.auth.TokenAuthentication',),
    }
    

    The issue here is that DEFAULT_AUTHENTICATION_CLASSES is set to knox.auth.TokenAuthentication, this means that all views will have this as their default auth class thus needs a token including the knox login view itself. By adding 'rest_framework.authentication.BasicAuthentication' , auth classes will be tested in sequence until one of them works, so for login, you can now do as an example:

    curl --location --request POST 'http://127.0.0.1:8000/api/v1/auth/login/' \ --header 'Authorization: Basic username:password'
    
    0 讨论(0)
  • 2021-01-21 21:06

    AuthToken.objects.create(user) returns two values - token instance and token key

    0 讨论(0)
提交回复
热议问题