Docs

Call API Using Authorization Code Flow with PKCE

This tutorial will help you call your own API from a native/mobile app using the Authorization Code Flow with PKCE. If you want to learn how the flow works and why you should use it, see Authorization Code Flow with Proof Key for Code Exchange (PKCE). If you want to learn to add login to your native/mobile app, see Add Login Using Authorization Code Flow with PKCE.

Auth0 makes it easy for your app to implement the Authorization Code Flow with Proof Key for Code Exchange (PKCE) using:

  • Auth0 Mobile SDKs: The easiest way to implement the flow, which will do most of the heavy-lifting for you. Our Mobile Quickstarts will walk you through the process.
  • Authentication API: If you prefer to roll your own, keep reading to learn how to call our API directly.

Prerequisites

Before beginning this tutorial:

  • Register the Application with Auth0.

    • Select an Application Type of Native.
    • Add an Allowed Callback URL of YOUR_CALLBACK_URL. Your callback URL format will vary depending on your platform. For details about the format for your platform, see our Native/Mobile Quickstarts.
    • Make sure the Application's Grant Types include Authorization Code.
    • If you want your Application to be able to use Refresh Tokens, make sure the Application's Grant Types include Refresh Token.
  • Register your API with Auth0

    • If you want your API to receive OpenID Connect (OIDC)Refresh Tokens to allow it to obtain new tokens when the previous ones expire, enable Allow Offline Access.

Steps

  1. Create a code verifier: Generate a code_verifier that will be sent to Auth0 to request tokens.
  2. Create a code challenge: Generate a code_challenge from the code_verifier that will be sent to Auth0 to request an authorization_code.
  3. Authorize the user: Request the user's authorization and redirect back to your app with an authorization_code.
  4. Request Tokens: Exchange your authorization_code and code_verifier for tokens.
  5. Call your API: Use the retrieved Access Token to call your API.
  6. Refresh Tokens: Use a Refresh Token to request new tokens when the existing ones expire.

Optional: Explore Sample Use Cases

Create a Code Verifier

Create a code_verifier, which is a cryptographically-random key that will eventually be sent to Auth0 to request an authorization_code.

Create a Code Challenge

Generate a code_challenge from the code_verifier that will be sent to Auth0 to request an authorization_code.

Authorize the User

Once you've created the code_verifier and the code_challenge, you'll need to get the user's authorization. This is technically the beginning of the authorization flow, and this step may include one or more of the following processes:

  • Authenticating the user;
  • Redirecting the user to an Identity Provider to handle authentication;
  • Checking for active scopesSingle Sign-on (SSO) sessions;
  • Obtaining user consent for the requested permission level, unless consent has been previously given.

To authorize the user, your app must send the user to the authorization URL, including the code_challenge you generated in the previous step and the method you used to generate the code_challenge.

Example authorization URL

Parameters

Note that for authorizing a user when calling a custom API, you:

  • must include an audience parameter
  • can include additional scopes supported by the target API
Parameter Name Description
response_type Denotes the kind of credential that Auth0 will return (code or token). For this flow, the value must be code.
code_challenge Generated challenge from the code_verifier.
code_challenge_method Method used to generate the challenge (e.g., S256). The PKCE spec defines two methods, S256 and plain, the former is used in this example and is the only one supported by Auth0 since the latter is discouraged.
client_id Your application's Client ID. You can find this value in your Application Settings.
redirect_uri The URL to which Auth0 will redirect the browser after authorization has been granted by the user. The Authorization Code will be available in the code URL parameter. You must specify this URL as a valid callback URL in your Application Settings.

Warning: Per the OAuth 2.0 Specification, Auth0 removes everything after the hash and does not honor any fragments.
scope The scopes for which you want to request authorization. These must be separated by a space. You can request any of the standard OpenID Connect (OIDC) scopes about users, such as profile and email, custom claims conforming to a namespaced format, or any scopes supported by the target API (e.g., read:contacts). Include offline_access to get a Refresh Token (make sure that the Allow Offline Access field is enabled in the Application Settings).
audience The unique identifier of the API your mobile app wants to access. Use the Identifier value on the Settings tab for the API you created as part of the prerequisites for this tutorial.
state (recommended) An opaque arbitrary alphanumeric string your app adds to the initial request that Auth0 includes when redirecting back to your application. To see how to use this value to prevent cross-site request forgery (CSRF) attacks, see Mitigate CSRF Attacks With State Parameters.

As an example, your HTML snippet for your authorization URL when calling an API might look like:

Response

If all goes well, you'll receive an HTTP 302 response. The authorization code is included at the end of the URL:

Request Tokens

Now that you have an Authorization Code, you must exchange it for tokens. Using the extracted Authorization Code (code) from the previous step, you will need to POST to the token URL sending along the code_verifier.

Example POST to token URL




Parameters

Parameter Name Description
grant_type Set this to "authorization_code".
code_verifier The cryptographically-random key that was generated in the first step of this tutorial.
code The authorization_code retrieved in the previous step of this tutorial.
client_id Your application's Client ID. You can find this value in your Application Settings.
redirect_uri The valid callback URL set in your Application settings. This must exactly match the redirect_uri passed to the authorization URL in the previous step of this tutorial. Note that this must be URL encoded.

Response

If all goes well, you'll receive an HTTP 200 response with a payload containing access_token, refresh_token, id_token, and token_type values:

You should validate your tokens before saving them. To learn how, see Validate an ID Token and Validate an Access Token.

ID Tokens contain user information that must be decoded and extracted.

Access Tokens are used to call the Auth0 Authentication API's /userinfo endpoint or another API. If you are calling your own API, the first thing your API will need to do is verify the Access Token.

Refresh Tokens are used to obtain a new Access Token or ID Token after the previous one has expired. The refresh_token will only be present in the response if you included the offline_access scope and enabled Allow Offline Access for your API in the Dashboard.

Refresh Tokens must be stored securely since they allow a user to remain authenticated essentially forever.

Call your API

To call your API from a native/mobile application, the application must pass the retrieved Access Token as a Bearer token in the Authorization header of your HTTP request.




Refresh Tokens

You have already received a Refresh Token if you've been following this tutorial and completed the following:

  • configured your API to allow offline access
  • included the offline_access scope when you initiated the authentication request through the authorize endpoint

You can use the Refresh Token to get a new Access Token. Usually, a user will need a new Access Token only after the previous one expires or when gaining access to a new resource for the first time. It's bad practice to call the endpoint to get a new Access Token every time you call an API, and Auth0 maintains rate limits that will throttle the amount of requests to the endpoint that can be executed using the same token from the same IP.

To refresh your token, make a POST request to the /oauth/token endpoint in the Authentication API, using grant_type=refresh_token.

Example POST to token URL




Parameters

Parameter Name Description
grant_type Set this to "refresh_token".
client_id Your application's Client ID. You can find this value in your Application Settings.
refresh_token The Refresh Token to use.
scope (Optional) A space-delimited list of requested scope permissions. If not sent, the original scopes will be used; otherwise you can request a reduced set of scopes. Note that this must be URL encoded.

Response

If all goes well, you'll receive an HTTP 200 response with a payload containing a new access_token, its lifetime in seconds (expires_in), granted scope values, and token_type. If the scope of the initial token included openid, then the response will also include a new id_token:

You should validate your tokens before saving them. To learn how, see Validate an ID Token and Validate an Access Token.

Sample Use Cases

Customize Tokens

You can use Rules to change the returned scopes of Access Tokens and/or add claims to Access and ID Tokens. To do so, add the following rule, which will run after the user authenticates:

Namespacing Custom Claims

Auth0 returns profile information in a structured claim format as defined by the OpenID Connect (OIDC) specification. This means that custom claims added to ID Tokens or Access Tokens must conform to a namespaced format to avoid possible collisions with standard OIDC claims.

View Sample Application: Mobile App + API

For an sample implementation, see the Mobile + API architecture scenario. This series of tutorials is accompanied by a code sample that you can access in GitHub.

Keep Reading