Authentication in React using JWTs (JSON Web Tokens) with access and refresh tokens is a common approach to manage user sessions securely and efficiently. Here’s a detailed explanation of how this works:
1. JWT Basics
A JSON Web Token (JWT) is a compact, URL-safe token composed of three parts: a header, a payload, and a signature.
Header: Typically consists of two parts:
- the type of the token (JWT) and
- the signing algorithm (e.g., HMAC SHA256).
Payload: Contains the claims, which are statements about an entity (typically, the user) and additional data. Common claims include iss (issuer), exp (expiration time), sub (subject), and aud (audience).
Signature: Ensures that the token hasn’t been altered. It is created by combining the encoded header, encoded payload, a secret, and the algorithm specified in the header.
2. Access and Refresh Tokens
Access Token: A short-lived token (e.g., 15 minutes) used to access protected resources. It contains enough information to identify a user and their permissions.
Refresh Token: A long-lived token (e.g., 7 days, 30 days) used to obtain a new access token once the old one expires. It is stored securely and is only sent to the server during the refresh process.
3. Workflow in React
Initial Authentication
Login Request:
The user logs in by providing their credentials (username and password). This login credentials need to passed via HTTPS.
Detail article on HTTPS – Login credential over network layer
The React application sends a POST request to the authentication server with these credentials.
Token Issuance:
If the credentials are valid, the server generates an access token and a refresh token.
The server sends both tokens back to the client.
Storing Tokens:
The React application receives the tokens and stores them securely, typically in memory or in a secure storage mechanism like HTTP-only cookies or secure local storage.
Token Refreshing:
When the access token expires, the client uses the refresh token to request a new access token from the authentication server.
The server verifies the refresh token, and if valid, issues a new access token.
The client updates its stored access token and continues making requests.
4. Token Expiry and Refresh
Token Expiry:
When the access token expires, the client will typically receive a 401 Unauthorized response.
Refresh Token Request:
The React application detects the expired access token and sends a request to the server to get a new access token using the refresh token.
New Access Token:
If the refresh token is valid, the server issues a new access token and sometimes a new refresh token.
The client stores the new access token and continues to make authenticated requests.
This request to the new token is made at the interceptor layer & will re-try the actual API call which client requested