Mitigate replay attacks when using the Implicit Grant

Heads up! As part of our efforts to improve security and standards-based interoperability, we have implemented several new features in our authentication flows and made changes to existing ones. For an overview of these changes, and details on how you adopt them, refer to Introducing OIDC Conformant Authentication.

To mitigate replay attacks when using the Implicit Grant, a cryptographic nonce must be sent on authentication requests as required by the OpenID Connect specification.

The nonce is generated by the application, sent as a nonce query string parameter in the authentication request, and included in the ID Token response from Auth0. This allows applications to correlate the ID Token response from Auth0 with the initial authentication request.

For more information on where to include the nonce, see How to Implement the Implicit Grant.

Generate a cryptographically random nonce

One way to generate a cryptographically random nonce is to use a tool like Nano ID or similar. This does require you to bundle the tool with your JavaScript code, however. If that's not possible, you can take advantage of the fact that modern browsers can use the Web Crypto API to generate cryptographically secure random strings for use as nonces.

function randomString(length) {
    var charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._~'
    result = ''

    while (length > 0) {
        var bytes = new Uint8Array(16);
        var random = window.crypto.getRandomValues(bytes);

        random.forEach(function(c) {
            if (length == 0) {
                return;
            }
            if (c < charset.length) {
                result += charset[c];
                length--;
            }
        });
    }
    return result;
}

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 value

For example:

window.localStorage.setItem('nonce', randomString(16));

Validate the ID Token

Once Auth0 responds with an ID Token, 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
}