20 Mar 2024
Beginner
JWT (JSON Web Token) authentication works in the following simple points:
-
Token Creation:
- When a user logs in or authenticates, the server creates a JWT containing user's information like user ID, role, etc.
- This JWT is cryptographically signed by the server using a secret key.
-
Token Transmission:
- The server sends this JWT back to the client as part of the authentication process, typically in the response headers or body.
-
Token Storage:
- The client (typically a web browser or a mobile app) stores this token securely, usually in local storage, session storage, or cookies.
-
Token Usage:
- For every subsequent request to the server, the client sends this JWT along with the request, usually in the Authorization header as a Bearer token.
-
Token Verification:
- The server receives the JWT with each request.
- It verifies the signature of the JWT using the secret key it shares with the client.
- If the signature is valid and the token hasn't expired, the server trusts the information contained within it.
-
Access Control:
- The server extracts the user's information from the JWT and uses it to determine whether the user has the necessary permissions to access the requested resources.
-
Token Expiry:
- JWTs often have an expiration time (exp) set in them. Once expired, they are no longer valid for authentication, and the user needs to re-authenticate.
-
Logging Out:
- Since JWTs are stateless, there is no direct way to "log out" by invalidating a token.
- To invalidate a JWT, the server must either maintain a blacklist of revoked tokens or rely on the token's expiration time.
In summary, JWT authentication involves creating a token upon authentication, sending it to the client, which then includes it in subsequent requests to access protected resources. The server verifies the token's authenticity and grants access based on the contained user information.