Azure AD B2C
Nonce: Mitigate replay attacks when using implicit grant
When using the implicit grant, a cryptographic nonce must be sent on authentication requests in order to mitigate replay attacks.
On this page
Introduction
When using the implicit grant, a cryptographic nonce must be sent on authentication requests in order to mitigate replay attacks as required by the OpenID Connect specification.
The nonce is generated by the client, sent as a nonce query string parameter in the authentication request, and included in the id_token response from the authorization endpoint. This allows clients to correlate the id_token response from the authorization server with the initial authentication request.
Generate a cryptographically random nonce
Modern browsers can use the Web Crypto API to generate cryptographically secure random strings to use as nonces.
Here is a JavaScript code example on how to generate a nonce value:
function randomString(length) {
var bytes = new Uint8Array(length);
var random = window.crypto.getRandomValues(bytes);
var result = [];
var charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._~'
random.forEach(function (c) {
result.push(charset[c % charset.length]);
});
return result.join('');
}Persist nonces across requests
The generated nonce must be persisted in your web application using any of the following methods:
- HttpOnly session cookie
- HTML5 local storage
Example:
window.localStorage.setItem('nonce', randomString(16));Validate the id_token
Once an id_token has been received, this token must be validated and decoded as usual. Its nonce claim must contain the exact same value that was sent in the request. If not, authentication should be rejected by the application.
var jwt = '...'; // validated and decoded ID token body
if (jwt.nonce === window.localStorage.getItem('nonce')) {
// Nonce is OK
} else {
// Nonce is not OK! Token replay attack might be underway
}Source: Auth0 - Mitigate replay attacks when using the Implicit Grant