Part 3 - OAuth2 token authentication

    You need a fully-functional OAuth2 provider which is able to release access tokens: just follow the steps in the part 1 of the tutorial. To enable OAuth2 token authentication you need a middleware that checks for tokens inside requests and a custom authentication backend which takes care of token verification. In your settings.py:

    You will likely use the django.contrib.auth.backends.ModelBackend along with the OAuth2 backend (or you might not be able to log in into the admin), only pay attention to the order in which Django processes authentication backends.

    If you put the OAuth2 backend before AuthenticationMiddleware, or AuthenticationMiddleware is not used at all, it will try to authenticate user with the OAuth2 access token and set request.user and request._cached_user fields so that AuthenticationMiddleware (when active) will not try to get user from the session.

    If you use SessionAuthenticationMiddleware, be sure it appears before OAuth2TokenMiddleware. However SessionAuthenticationMiddleware is NOT required for using django-oauth-toolkit.

    To check everything works properly, mount the view above to some url:

    You should have an registered at this point, if you don’t, follow the steps in the previous tutorials to create one. Obtain an Access Token, either following the OAuth2 flow of your application or manually creating in the Django admin. Now supposing your access token value is 123456 you can try to access your authenticated view: