JWT and web security

Pasted image 20250210002807.png

{8EBF1CB3-15BF-40D2-A459-F987C7A079A4}.png

{791A3F6E-578A-4E1D-AEBA-4EA97D3DEF4F}.png

{228536E9-B3B3-4095-BC76-D360C69C1675}.png

{A7EEF87C-72E4-413B-B052-3DD722C0EE0C}.png

Pasted image 20250210003513.png

Pasted image 20250210003658.png

{75211E5C-D976-4095-BAC7-85534CBF763F}.png

{BCDDE510-8CDD-48F7-A912-58A773A620FB}.png


Pasted image 20250210003900.png

{DFAE68CA-6D21-4769-A637-0D0C2B0C7DAD}.png

{A8EE68D2-19DC-4175-B982-25CF0C4A9186}.png

{BC5B7770-B353-40D6-93B8-8FD069FF568E}.png

{C004FEBE-FC53-48E5-BDF3-217C1B65B658}.png


When saving JWT tokens, the best storage method depends on your security requirements and the type of token (access vs. refresh):

Best Practices for Storing JWT Tokens

1. Access Tokens (Short-lived)

2. Refresh Tokens (Long-lived)

  1. Store access tokens in memory.
  2. Store refresh tokens in HttpOnly Secure Cookies.
  3. Use the refresh token to obtain a new access token when needed.

Would you like guidance on implementing this in your React or Node.js app?


When using MSAL for React (@azure/msal-react), JWT tokens (ID token, access token, and refresh token equivalents) are stored based on the configured cache location in MSAL Configuration. The storage options are:

Where MSAL Saves JWT Tokens?

MSAL uses cacheLocation in its configuration to determine where it stores tokens:

Default Behavior

By default, MSAL stores tokens in sessionStorage, meaning:

How to Configure Storage in MSAL?

You can specify where to store tokens in the cache configuration:

import { PublicClientApplication } from "@azure/msal-browser";

const msalConfig = {
  auth: {
    clientId: "YOUR_CLIENT_ID",
    authority: "https://login.microsoftonline.com/YOUR_TENANT_ID",
    redirectUri: "/",
  },
  cache: {
    cacheLocation: "localStorage", // or "sessionStorage"
    storeAuthStateInCookie: true, // Helps in certain browsers (IE11, Safari)
  }
};

const msalInstance = new PublicClientApplication(msalConfig);

Storage Options & Security Considerations

Storage Type Persistence Security Use Case
sessionStorage (default) Cleared on browser close Less risk of XSS attacks Recommended for security
localStorage Persists after browser close Vulnerable to XSS Use only if session persistence is required
Memory (Custom implementation) Cleared on page refresh Most secure, prevents XSS Requires custom handling

How to Clear Tokens?

To remove the tokens:

msalInstance.logoutRedirect(); // Logs out & clears tokens
msalInstance.logoutPopup(); // Logs out using a popup

Would you like help handling token expiration or silent authentication in your React app?