skip to Main Content

I am using django-rest-social-auth package to allow users authenticate in my Django rest app. I was able to retrieve a token from facebook for an user. Now, I don’t know how to use that token. I am trying to access an endpoint that requires logged in users, but I see accesses only as anonymous user when I debug. I’ve been googleing this issue and tried a lot of different methods (different cookies, url params, etc.).

This is my particular case:

views.py

@login_required
def home(request):
    return render(request, 'home.html')

I obtained my token calling http://localhost:8000/api/login/social/token/ (I was following the django-rest-social-auth readme) and it looks like:

{"token": "4571b2dce1f3abec34b28a4c7bd981c248a30698"}

I have that token linked with my user and I can see it in my admin (Home › Auth Token › Tokens)

If I delete the @login_required I can access home without any issue. How can I send a request via postman to access that resource using my token?

2

Answers


  1. Chosen as BEST ANSWER

    After some study I found a solution. There are 2 considerations here:

    • Django needs permission and authentication classes

    My views.py now looks like this:

    class AuthDetailView(BaseDetailView):
        authentication_classes = (TokenAuthentication, )
        permission_classes = IsAuthenticated,
        def get(self, request):
            return render(request, 'home.html')
    

    Notice that I don't have the @login_required anymore.

    • Django likes the authorization header with a 'Token' instead a 'Bearer' in front of it

    When I make a call to my api, auth header should be like Authorization: Token 4571b2dce1f3abec34b28a4c7bd981c248a30698 instead Authorization: Bearer 4571b2d...

    After this changes, request.user is automatically bound to the user previously linked to the token above.


  2. Add Authorization: Bearer 4571b2dce1f3abec34b28a4c7bd981c248a30698 to the headers as shown below:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search