Jwt(Json Web Token)is an open standard for securely transmitting information between parties as a Json object.
Structure of Jwt
Jwt consist of three parts.
Header : Contain metadata about the token, such as the algorithm used for signing.
Payload : Include the actual data you want to share.
Signature : A cryptographic "seal" that ensures the data hasn't been tempered with.
These three parts are combined into a single, encoded String that is sent between the client and the server.
Why use Jwt
Authentication : After a user logs in, the server generates a Jwt and send it to client. The client stores this token and send it back with every request to prove, "I'm authenticated user!"
Authorization : The Jwt can include roles, So the server can easily check what the user is allowed to do.
How Jwt works
1- The user logs in with their credentials (username, pw etc..)
2- The server creates 'Refresh Token' and 'Access Token' and then send both token to client.
Refresh Token: A short lived token (ex) 15min)
Access Token: A long lived token (ex) 7 days)
3- The client stores
the Access Token (ex) RAM mememory, HttpOnly cookie)
and Refresh Token. (ex) HttpOnly cookie)
To store token in localStorage or SessionStorage isn't recommended, Because they are vulnerable to XSS(Cross-Site Scripting) attack.
4- The client sends the access token with every request to the server (Authorization header as Bearer )
5- The server verifies the token and processes the request.
6- Once the access token expires, the client can't use it anymore protected resources, So we should be issued access token by using refresh token.
7- If the refresh token expires, the user should log in again with their credentials.
How to use
(Planned to be added)
Adding
XSS: XSS allows attackers to inject and excute malicious scripts in a user's browser.
CSRF: CSRF tricks an authentication user into performing unintended actions on the website where the user is already authenticated.
Top comments (0)