Saturday, 24 June 2023

Django oauth2 request.user returns AnonymousUser

I'm a Django newbie and am trying to create an API to the backend for use by iOS client. Currently I am testing my API access with curl.

I have successfully generated access tokens using:

curl -X POST -d "grant_type=password&username=example_user&password=example_password" http://clientID:clientSecret@localhost:8000/o/token/

which generated the following response -

{
    "access_token": "oAyNlYuGVk1Sr8oO1EsGnLwOTL7hAY", 
    "scope": "write read", 
    "expires_in": 36000, 
    "token_type": "Bearer", 
    "refresh_token": "pxd5rXzz1zZIKEtmqPgE608a4H9E5m"
}

I then used the access token to try to access the following class view:

from django.http import JsonResponse
from oauth2_provider.views.generic import ProtectedResourceView
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator

class post_test(ProtectedResourceView):

    def get(self, request, *args, **kwargs):
        print(request.user)
        return JsonResponse({'Message': "You used a GET request"})

    def post(self, request, *args, **kwargs):
        print(request.user)
        return JsonResponse({'Message': 'You used a POST request'})

    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(post_test, self).dispatch(*args, **kwargs)

with the following curl request:

curl -H "Authorization: Bearer oAyNlYuGVk1Sr8oO1EsGnLwOTL7hAY" -X GET http://localhost:8000/api/post-test/

Which properly responds to the client with:

{"Message": "You used a GET request"}

But in the console, where I expect the request.user variable, I get AnonymousUser.

Isn't the token supposed to be assigned to example_user? Shouldn't that be what request.user returns?



from Django oauth2 request.user returns AnonymousUser

No comments:

Post a Comment