Search code examples
django-rest-frameworktokendjango-rest-auth

how to pass header from views in token authentication in DRF


I've 2 apps in my django rest framework project, namely 'accounts' and 'trello'. I've used token authentication of DRF. I've authenticated(validated) and generated token for the users trying to login in the views of my 'accounts' app. And for one of the views of my 'trello' app, I've set authentication_classes = (TokenAuthentication,) and permission_classes = [IsAuthenticated, ] .I also have done necessary settings for DEFAULT_AUTHENTICATION_CLASSES.

My question is: How do I send header with the token key generated from my views of 'account' app to the view where it needs the user to be authenticated i.e. for the view in 'trello' ?

I've tried it this way:

accounts/views.py:

import requests

myurl = "http://localhost:8000/trello/create/board/"

class LoginView(APIView):

permission_classes = [AllowAny]
serializer_class = UserLoginSerializer

def post(self, request, *args, **kwargs):
    data = request.data
    serializer = UserLoginSerializer(data=data, context={'request': request})
    serializer.is_valid(raise_exception=True)
    print(serializer.validated_data['user'])
    user = serializer.validated_data['user']
    print("user", user)
    token, created = Token.objects.get_or_create(user=user)
    requests.post(myurl, data=serializer.validated_data, headers={'Authorization': 'Token {}'.format(token)})
    # django_login(request, user)
    return Response({'token': token.key},
                    status=HTTP_200_OK)

trello/views.py:

I actually do not know how to catch the data here.I tried to post from the account's views using django requests. I tried using get method here but it is not working as I want it to. I probably have tried this the wrong way, but can anyone correct this?


Solution

  • You're probably missing the token authentication flow. Here is what happens:

    1. A client requests for a token using login and password
    2. Your login view (or obtain-token view as I prefer to call it) verifies the user credentials presented by the client and issues a token. Note that you don't need to perform any Django login here, all you need do is issue token
    3. In subsequest requests, clients adds the token to the Auth header and DRF's TokenAuthentication class authenticates (this is where the login occurs) the request and adds the user object to the request
    4. Voila! all your requests are now being authenticated and you can add the necessary permissions to your views (trello view for example)