Django REST Framework: using TokenAuthentication with browsable API

前端 未结 3 1187
我在风中等你
我在风中等你 2020-12-29 23:08

I\'m following the DRF docs to setup TokenAuthentication, and can\'t get it working with the browsable API. I believe I\'ve added the proper lines in settings.py

相关标签:
3条回答
  • 2020-12-29 23:43

    You can use a browser plugin to set token in the header. I'm using Modheader which is free.

    The example of setting the header:

    I wrote a blog post on how this can be done: link to post.

    I like this solution because you don't need to change the auth classes.

    0 讨论(0)
  • 2020-12-29 23:50

    You can't use the browsable api with TokenAuthentication. You have to add SessionAuthtication to your settings (http://www.django-rest-framework.org/api-guide/authentication/#sessionauthentication):

    REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    
    0 讨论(0)
  • 2020-12-30 00:00

    I did:

    REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    

    and I added a custom auth class in api.py

    class CustomAuthToken(ObtainAuthToken):
    
        authentication_classes = [TokenAuthentication]
    
        def post(self, request, *args, **kwargs):
            ...
            return Response({...})
    

    See https://www.django-rest-framework.org/api-guide/authentication/#by-exposing-an-api-endpoint

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