# Nonce: Mitigate replay attacks when using implicit grant

Product: Azure AD B2C
Source: https://docs.fortytwo.io/Managed%20Azure%20AD%20B2C/e6-Nonce/

## Introduction

When using the [implicit grant](https://docs.fortytwo.io/Managed%20Azure%20AD%20B2C/e4-OAuth-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](https://www.w3.org/TR/WebCryptoAPI/) to generate cryptographically secure random strings to use as nonces.

Here is a JavaScript code example on how to generate a  **nonce** value:

```javascript
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:

```javascript
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.

```javascript
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](https://auth0.com/docs/get-started/authentication-and-authorization-flow/mitigate-replay-attacks-when-using-the-implicit-flow)
