[Fixed]-Appropriate choice of authentication class for python REST API used by web app


Django REST Framework gives you the flexibility of having multiple authentication methods. Since I’ve got some time, and it will be useful to future visitors who have similar questions, I’ll outline the benefits of the most common authentication methods.

Initially its client would be a web application, but conceivably future clients could include mobile applications.

Typically when working with web applications that are on the same domain and Django instance as the API, most people use SessionAuthentication as it interacts with the server using the existing authentication methods. Authentication works seamlessly, so you don’t need to go through the second authentication step.

Most APIs also support some form of BasicAuthentication, most likely because it is the easiest to test with but also because it is the easiest to implement. For your web application, this isn’t the recommended authentication method, but for your mobile application it’s not uncommon to see it being used. I personally would recommend a token-based authentication, so you don’t have to worry about clients intercepting user’s credentials.

It looks like TokenAuthentication would meet my needs.

Many people use TokenAuthentication because it is relatively simple to understand and use, and it seems to meet everyone’s needs at first. Tokens are directly attached to users, and they do not automatically rotate (though you can make them automatically rotate), so every client working on behalf of the user gets the same token. This can be an issue if you ever need to revoke the token, as all other clients will have their token invalidated as well.

I would rather avoid the cognitive overhead of OAuth unless there is a compelling security reason to go that way.

OAuth 2 (OAuth2Authentication) gives you token rotation and token expiration on top of the benefits of TokenAuthentication. There’s also the benefit of being able to revoke individual tokens without affecting other clients who are authenticating for the user. You can also limit clients to individual areas of your API through the use of scopes, which is useful if you have certain areas of the API that are more often used than others.

I’m also going to mention JSON Web Tokens, because while I haven’t used it, it’s been showing up quite a bit in the support channels. It works very similar to TokenAuthentication as far as retrieving tokens, but it has the added benefit of unique tokens for clients and token expiration.

Leave a comment