J Freebird
J Freebird

Reputation: 3910

Retrieve User Info in OAuth2 Protected Views

I'm using django-oauth-toolkit for my app's OAuth2 implementation. I have the following code:

    from oauth2_provider.decorators import protected_resource
    User = get_user_model()

    @protected_resource(scopes=['ifttt'])
    @api_view(['GET'])
    def user_info(request):
        username = request.user.username
        u_id     = request.user.id
        data = {}
        data['name'] = username
        data['id'] = u_id

        rst = {}
        rst['data'] = data
        return Response(rst, status=status.HTTP_200_OK)

The problem is that the username and ID returned is empty. It seems that the user object cannot be retrieved as if the function is called by an anonymous user, which is not true since OAuth2 requires user authentication.

Maybe it's because it is the client app which the user authorized that is making the call, instead of the user itself? If so, how can I get the user object corresponded to the application? Thanks.

Edit:

I tried to put request.user to response but failed, the error is Anonymous user is not JSON serializable. So django does think the request is from an anonymous user.

Upvotes: 1

Views: 2341

Answers (2)

Ilker
Ilker

Reputation: 46

A latecomer here but in case someone comes across this question later, actual answer is about Django configuration.

Follow the instructions on this page: https://django-oauth-toolkit.readthedocs.io/en/latest/tutorial/tutorial_03.html

If you have the right AUTHENTICATION_BACKENDS and MIDDLEWARE_CLASSES, request.user will be populated after a token based authentication.

Upvotes: 2

J Freebird
J Freebird

Reputation: 3910

Use the access token in the Header to retrieve the corresponding user. Here the 'Authorization' is like: 'Bearer {token}'.

from oauth2_provider.models import AccessToken

def user_info(request):
    app_tk = request.META["HTTP_AUTHORIZATION"]
    m = re.search('(Bearer)(\s)(.*)', app_tk)
    app_tk = m.group(3)
    acc_tk = AccessToken.objects.get(token=app_tk)
    user = acc_tk.user

    username = user.username
    u_id     = user.id
    # other codes and return

Upvotes: 2

Related Questions