Best Practices for OAuth 2.0 in Azure AD


This topic describes best practice behavior for using OAuth 2.0 authorization in Azure Active Directory (Azure AD).

Use the State Parameter

The state parameter is optional, but recommended in requests for an authorization code in the Authorization Code Grant Flow. To use the state parameter, the client application generates a pseudo-random value that would be hard for an attacker to guess and is not reused, such as a GUID. The client sends the state parameter and value in the request. The response should include a state parameter with the same value. When the client receives the response, they verify that the state values are identical before proceeding.

The state parameter helps to detect cross-site request forgery (CRSF) attacks against the client. For more information about CRSF attacks, see Cross-Site Request Forgery in Section 10.12 of The OAuth 2.0 Authorization Framework.

Cache Access Tokens

To minimize network calls from the client application and their associated latency, the client application should cache access tokens for the token lifetime that is specified in the OAuth 2.0 response. To determine the token lifetime, use either the expires_in or expires_on parameter values.

If a web API resource returns an invalid_token error code, this might indicate that the resource has determined that the token is expired. If the client and resource clock times are different (known as a "time skew"), the resource might consider the token to be expired before the token is cleared from the client cache. If this occurs, clear the token from the cache, even if it is still within its calculated lifetime.

Handling Refresh Tokens

Refresh tokens do not have specified lifetimes. Typically, the lifetimes of refresh tokens are relatively long. However, in some cases, refresh tokens expire, are revoked, or lack sufficient privileges for the desired action. The client application needs to expect and handle errors returned by the token issuance endpoint correctly. When you receive a response with a refresh token error, discard the current refresh token and request a new authorization code or access token. In particular, when using a refresh token in the Authorization Code Grant flow, if you receive a response with the interaction_required or invalid_grant error codes, discard the refresh token and request a new authorization code.

See Also

OAuth 2.0 in Azure AD