DJango Oauth Toolkit - Authenticating users with access tokens

(Comments)

This is the continuation of our previous post which explains how to build APIs that are protected with OAuth2. We are using Django OAuth Toolkit and I am assuming that you have already followed the previous post.

Well, we have protected our API end-points with OAuth2 but we need to identify the user (resource owner in OAuth terms) who has provided the access token. To understand the scenario let us change our previous view. Our view previously was

class MyProtectedEndPoint(ProtectedResourceView):
    def get(self, request, *args, **kwargs):
        return HttpResponse('Hello, there!!\n')

Let us change it slightly to the following.

class MyProtectedEndPoint(ProtectedResourceView):
def get(self, request, *args, **kwargs):
    if request.user.is_authenticated():
        return HttpResponse(
            'Hello there! You are acting on behalf of "%s"\n'
            % (request.user))
    else:
        return HttpResponse('Hello! I do not recognize you\n')

Now let us make a request to the view using curl with the following command.

curl -i -H "Accept: application/json" -H "Authorization: Bearer 3EhQHLbGv5rJ4cCaNnACnvwed89N1c" -X GET http://localhost:8000/api/posts/protected_view/

The result should look something like this.

HTTP/1.0 200 OK
Date: Mon, 10 Jul 2017 07:08:54 GMT
Server: WSGIServer/0.2 CPython/3.5.2
X-Frame-Options: SAMEORIGIN
Content-Type: text/html; charset=utf-8
Content-Length: 30
Vary: Cookie

Hello! I do not recognize you

The client (curl in our case) though has the credentials to access the API, our service was clearly unable to identify on whose behalf it is making the requests. Say, the client requests the profile information of the user, our service fails to serve the right user's data.

To resolve this we need to configure our authentication backends and middleware. In our django application settings set the AUTHENTICATION_BACKENDS and MIDDLEWARE to

AUTHENTICATION_BACKENDS = [
    'oauth2_provider.backends.OAuth2Backend',
    'django.contrib.auth.backends.ModelBackend' # Only if you want to use admin
]

MIDDLEWARE = [
    # ... other middlewares like
    # 'django.contrib.auth.middleware.AuthenticationMiddleware',
    'oauth2_provider.middleware.OAuth2TokenMiddleware',
    # ... 
]

That is all we need to do to identify the resource owner (user). Now when we run our curl command, the result is as follows.

curl -i -H "Accept: application/json" -H "Authorization: Bearer 3EhQHLbGv5rJ4cCaNnACnvwed89N1c" -X GET http://localhost:8000/api/posts/protected_view/

HTTP/1.0 200 OK
Date: Mon, 10 Jul 2017 07:09:00 GMT
Server: WSGIServer/0.2 CPython/3.5.2
Content-Type: text/html; charset=utf-8
Content-Length: 48
Vary: Authorization, Cookie
X-Frame-Options: SAMEORIGIN

Hello there! You are acting on behalf of "ravi"

Now that these settings are in place, we can also use the login_required decorator from django.contrib.auth.decorators.

Comments

Recent Posts

Archive

2022
2021
2020
2019
2018
2017
2016
2015
2014

Tags

Authors

Feeds

RSS / Atom