Additional Parameters
The system supports nonce (to mitigate Replay attacks) and state (to maintain state and mitigate CSRF).
nonce
Case-sensitive string used to associate a client session with an id_token and to mitigate Replay attacks. The value is transmitted unchanged from the authentication request to the id_token. If present in the id_token, the client must verify that the nonce Claim value equals the nonce parameter value sent in the request.
Example
Nonce in request:
&nonce=n-0S6_WzA2MjIn ID Token:
{
"nonce": "n-0S6_WzA2Mj",
...
}Validation
const generatedNonce = generateNonce();
sessionStorage.setItem('oauth_nonce', generatedNonce);
const authUrl = `...&nonce=${generatedNonce}`;
// In callback, after receiving ID Token:
const claims = decodeJWT(idToken);
const storedNonce = sessionStorage.getItem('oauth_nonce');
if (claims.nonce !== storedNonce) {
throw new Error('Nonce does not match - possible Replay attack');
}state
Opaque value used to maintain state between the request and Callback. Commonly, Cross-site Request Forgery (CSRF, XSRF) mitigation is done by linking the value of this parameter to a Browser cookie. If present in the authorization request, the provided value is transmitted unchanged to the Callback.
Example
State in request:
&state=af0ifjsldkjIn callback:
https://example.com.br/callback?code=50b9-ac5e-43-a9b6f8685&state=af0ifjsldkjValidation
const generatedState = generateState();
sessionStorage.setItem('oauth_state', generatedState);
const authUrl = `...&state=${generatedState}`;
// In callback:
const urlParams = new URLSearchParams(window.location.search);
const returnedState = urlParams.get('state');
const storedState = sessionStorage.getItem('oauth_state');
if (returnedState !== storedState) {
throw new Error('State does not match - possible CSRF attack');
}Helper Functions
function generateNonce() {
return btoa(Math.random().toString()).substring(0, 16);
}
function generateState() {
return btoa(Math.random().toString()).substring(0, 16);
}Best Practices
- Always use
stateto prevent CSRF attacks - Use
noncewhen you need to ensure the ID Token corresponds to the specific request - Store values securely (sessionStorage, httpOnly cookies, etc.)
- Always validate returned values before processing authentication
- Generate random and unique values for each request
