0
votes

The DRF documentation (https://www.django-rest-framework.org/api-guide/authentication/#authentication) states that

Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.

and

Session authentication is appropriate for AJAX clients that are running in the same session context as your website.

Yet most of the tutorials and StackOverflow questions/answers about Django Rest Framework Authentication suggest using Token authentication in most of the cases, even with webapps.

I'm implementing a webapp usingDjango/Django Rest Framework as the backend and Angular as the fron-end. Which authentication scheme should I use? What are the pros and cons of each?

1

1 Answers

0
votes

Session Based Authentication

In the session based authentication, the server will create a session for the user after the user logs in. The session id is then stored on a cookie on the user’s browser. While the user stays logged in, the cookie would be sent along with every subsequent request. The server can then compare the session id stored on the cookie against the session information stored in the memory to verify user’s identity and sends response with the corresponding state!

enter image description here

Token Based Authentication

Many web applications use JSON Web Token (JWT) instead of sessions for authentication. In the token based application, the server creates JWT with a secret and sends the JWT to the client. The client stores the JWT (usually in local storage) and includes JWT in the header with every request. The server would then validate the JWT with every request from the client and sends response.

enter image description here

The biggest difference here is that the user’s state is not stored on the server, as the state is stored inside the token on the client side instead. Most of the modern web applications use JWT for authentication for reasons including scalability and mobile device authentication.