
Things Every Developer Should Know: JSON Web Token.
JWTs are one of the most widely used methods for API authentication, providing a secure, stateless and scalable way to verify clients.
๐๐ฒ๐ฟ๐ฒโ๐ ๐ฎ ๐๐ถ๐บ๐ฝ๐น๐ฒ-๐๐ผ-๐๐ป๐ฑ๐ฒ๐ฟ๐๐๐ฎ๐ป๐ฑ ๐ฏ๐ฟ๐ฒ๐ฎ๐ธ๐ฑ๐ผ๐๐ป ๐ผ๐ณ ๐ต๐ผ๐ ๐ถ๐ ๐๐ผ๐ฟ๐ธ๐, ๐๐๐ฒ๐ฝ ๐ฏ๐ ๐๐๐ฒ๐ฝ:
๐ญ) ๐๐น๐ถ๐ฒ๐ป๐ ๐ฎ๐๐๐ต๐ฒ๐ป๐๐ถ๐ฐ๐ฎ๐๐ถ๐ผ๐ป
The client (a user, app, or device) provides credentials (eg; username/password) to the authentication server.
๐ฎ) ๐ฆ๐ฒ๐ฟ๐๐ฒ๐ฟ ๐๐ฒ๐ฟ๐ถ๐ณ๐ถ๐ฐ๐ฎ๐๐ถ๐ผ๐ป
The authentication server checks the credentials against its database or identity provider to confirm their validity.
๐ฏ) ๐๐ช๐ง ๐ถ๐๐๐๐ฎ๐ป๐ฐ๐ฒ
If authentication is successful, the server:
โ Generates a JWT with claims (eg; user ID, roles, permissions).
โ Signs the JWT using a secret key (HS256) or a private key (RS256).
๐ฐ) ๐ง๐ผ๐ธ๐ฒ๐ป ๐ฑ๐ฒ๐น๐ถ๐๐ฒ๐ฟ๐
The server sends the signed JWT back to the client in the response.
๐ฑ) ๐ฆ๐ฒ๐ฐ๐๐ฟ๐ฒ ๐๐๐ผ๐ฟ๐ฎ๐ด๐ฒ
The client stores the JWT securely to prevent unauthorized access. HTTP-only cookies are the most secure and widely used method.
๐ฒ) ๐๐ฃ๐ ๐ฟ๐ฒ๐พ๐๐ฒ๐๐๐ ๐๐ถ๐๐ต ๐๐ช๐ง
For each request to a protected API, the client includes the JWT in the Authorization header:
`Authorization: Bearer <JWT>`
๐ณ) ๐ฆ๐ฒ๐ฟ๐๐ฒ๐ฟ ๐๐ฎ๐น๐ถ๐ฑ๐ฎ๐๐ฒ๐ ๐๐ต๐ฒ ๐๐ช๐ง
The API server verifies the JWT before granting access by checking:
โ Signature โ Confirms token integrity (not tampered with).
โ Expiration โ Ensures the token hasnโt expired.
โ Audience (aud claim) โ Checks if the token is meant for this API.
โ Issuer (iss claim) โ Confirms the token was issued by a trusted authority.
If the JWT is valid, the server grants access to the requested resource. Otherwise, it rejects the request (401 Unauthorized).
๐ด) ๐ง๐ผ๐ธ๐ฒ๐ป ๐ฒ๐
๐ฝ๐ถ๐ฟ๐ฎ๐๐ถ๐ผ๐ป & ๐ฟ๐ฒ๐ณ๐ฟ๐ฒ๐๐ต
Since JWTs expire for security reasons, the client needs a refresh token to get a new one:
โณ Client sends refresh token to the server.
โณ Server verifies & issues a new JWT if the refresh token is valid.
โณ New JWT replaces the expired one, and the client continues making requests.




