A gentle introduction to JSON Web TokensGepostet von Michele am 30.03.2023
Introduction to the authentication problem
Developing an authentication and authorisation mechanism is a crucial point in designing an application, involving (at least) both client and server. But how do you handle an authenticated message exchange considering that HTTP is stateless?
The solution is establishing a session: upon authentication, the client receives from the authentication server a certain session-ID that allows them to recognize subsequent HTTP requests as authenticated. Such information:
- must be stored client-side;
- must be attached every time the client sends a request which is part of the session;
- can be implemented as a cookie, which is automatically handled by the browser and can be sent on secure connections only (secure option).
Once they have been introduced by the IETF (RFC 7519), JSON Web Tokens (JWT) become very popular for addressing this kind of problem.
JWT authentication flow
Once the client sends an authentication request (Login request), the server signs a payload which contains information about the user (at least a user ID and the expiration time) and sends it to the client (Signed JWT), which internally stores it.
From this time on, any client requests for a restricted resource (Data Request) will need the previously stored token (+Signed JWT) so that the server can verify the signature, extract the user information and eventually send the Response back. Note that this approach does not require the server to store any information about the session.
JWT is composed by three sections, separated by a dot:
- Header: a Base64-encoded string over the hashing algorithm and the token type.
- Payload: a Base64-encoded string over the JSON object that was sent back to the user during the Login (this object generally contains a user-ID, some user information, the timestamp of when the token was issued and the expiration time).
- Token signature: generated by hashing the concatenation of the previous sections using a secret key, which is a random string that only the server knows. It is essential for verifying that the information is unchanged, avoiding fake requests and impersonation attacks.
Hence, the previous schema can be seen as:
If you want to learn more (do you know how to deal with XSS and CSRF attacks?) or simply want to try to decode, verify and generate JWTs, please follow this link https://jwt.io/ … and have fun!