Django: Rest Framework authenticate header

前端 未结 5 1577
小鲜肉
小鲜肉 2020-12-23 02:36

Using Django REST API, I\'m trying to authenticate my request.

This is what I\'m trying to send:

Content-Type: application/json, Authentication: toke         


        
5条回答
  •  独厮守ぢ
    2020-12-23 03:02

    In my case this works:
    (Django REST Framework v3)

    settings.py

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

    views.py

    class Test(APIView):
        def get(self, request, format=None):   
            return Response({'Result': 'OK'})
    

    urls.py

    router.add_api_view('test', url(r'^test/', views.Test.as_view(),name='test'))
    

    Don't forget to send the token information in the header:

     Key: Authorization  
     Value: Token 76efd80cd6849ad7d35e04f1cc1eea35bdc20294
    

    To generate tokens you can use the following (somewhere in your code):

    from rest_framework.authtoken.models import Token            
    user = User.objects.get(username='')
    token = Token.objects.create(user=user)
    print(token.key)
    

提交回复
热议问题