How to get an access token with Confidential Authorization Code Grant
This topic demonstrates how to generate an access token manually using Authorization Code Grant authentication or with a refresh token. In the Confidential Authorization Code Grant flow, your client integration obtains consent from an individual to perform actions on their behalf, then receives an authorization code that can be exchanged for an access token, which is required to make API calls.
Note: Instead of generating the access token manually, you can also implement Confidential Authorization Code Grant authentication by:
- Using code from Quickstart and modifying it to meet your app’s needs. Quickstart generates a personalized project that contains an authorization code that you can use to implement Confidential Authorization Code Grant. The Multiple code examples, Authorization Code Grant, and JWT Grant Quickstart project implements and uses this Grant by default.
- Using refresh token methods from one of the SDKs.
Optional PKCE security layer You can use an additional security layer, Proof Key for Code Exchange (PKCE), to ensure that the app that finishes the flow is the one that started it. See Optional PKCE code challenge for details.
Walkthrough video
You can also see a walkthrough video of how to get an access token using Confidential Authorization Code Grant.
Prerequisites
To obtain an access token with Confidential Authorization Code Grant, you must meet the following prerequisites.
Step 1. Request the authorization code
Before you can make any API calls using Confidential Authorization Code Grant, you must get your user’s consent for your app to act for them.
To get this consent, open the accompanying Sample URI in your embedded browser, replacing the value of client_id with your integration key.
Your user will be prompted to sign in to their account and give consent for your app to make calls on their behalf.
After selecting Accept, if you used localhost as your redirect URI, your browser may attempt to load the query parameters as a web page. This will result in a display error message, which you can safely ignore. Select the value of the code query parameter in the page URI, then save it to use in the next step.
See details: Authorization code request syntax
The constructed URI for obtaining consent and getting an authorization code contains several parts:
-
A base path for the authentication service. This path differs depending on whether your app is in the developer environment or in production.
- For the developer environment, the base URI is
https://account-d.docusign.com/oauth/auth - For the production environment, the base URI is
https://account.docusign.com/oauth/auth
- For the developer environment, the base URI is
-
Your application’s integration key.
-
A Base64URL-encoded redirect URI that matches one of those configured for the application with the specified integration key.
-
A space-delimited list of the scopes your app needs. For this example, use the
signaturescope, which enables your app to call the eSignature REST API. -
A
response_typevalue ofcode, indicating that your app is using Authorization Code Grant. -
An optional state value that you can use to prevent CSRF and replay attacks. See Prevent attacks and redirect users with OAuth 2.0 State Parameters and OAuth replay attack mitigation for details.
-
An optional
login_hintthat enables you to prepopulate the email address field on the sign-in screen.
The accompanying URI syntax and Sample URI show how these values map to the sections of the URI.
After your user logs in and grants permission, your app will be able to make API calls on their behalf. A set of query parameters will be returned to the redirect URI; for the Authorization Code Grant flow, the code query parameter will be used in the next step.
Note: Redirect URIs cannot contain fragment components. If your app needs to use a fragment, record that fragment in the state parameter (which will be returned along with the redirect URI) and re-combine the fragment and the redirect URI in your app after the initial call to get the authorization code.
See How to obtain individual consent for details.
Step 2. Obtain the access token
To request an access token, send a POST request containing your authorization code to the Docusign authentication service.
- For the developer environment, the URI is
https://account-d.docusign.com/oauth/token - For the production environment, the URI is
https://account.docusign.com/oauth/token
Note: The authorization code is only viable for two minutes. If more than two minutes pass between obtaining the authorization code and attempting to exchange it for an access token, the operation will fail.
See details: Request elements
The request contains the following parameters.
In addition to the headers, the access token request contains a set of body parameters.
The access token contains the following fields.
Step 3. Get your user’s base URI
To make an API call to the Docusign platform, your application needs both an access token (which you obtained in the previous step), and a base URI that is unique to the user on whose behalf your application is making the API call.
To get the base URI, call the /oauth/userinfo endpoint, supplying your application’s access token as a header.
- For the developer environment, the URI is
https://account-d.docusign.com/oauth/userinfo - For the production environment, the URI is
https://account.docusign.com/oauth/userinfo
The request must contain an Authorization header that holds your access token.
If successful, this returns a set of data for each user who has granted consent and the account(s) that user is a member of, as shown by the Sample response.
You will need the account_id and the base_uri claims of the user that your application is acting on behalf of to make calls to a Docusign API.
Docusign enforces hourly limits on the number of /oauth/userinfo requests per user ID and per integration key. See User info endpoint limits for details.
Step 4. Use the access token to make an API call
Now that you’ve obtained an access token and the user info, your application is authenticated and has all of the information that it needs to make a call to a Docusign API. To make an eSignature REST API request, you must include:
- The acquired access token in the request’s Authorization header.
- The base URI for the request, built from the
account_idand thebase_uriof the user account.
For example, the syntax to call AccountBrands:list to return details about all of the brands associated with an account is:
GET restapi/v2.1/accounts/{accountId}/brands
Substituting the base URI of https://demo.docusign.net and API Account ID of 18b4799a-xxxx-xxxx-xxxx-b5b4b8a97604, the request path would be:
GET https://demo.docusign.net/restapi/v2.1/accounts/18b4799a-xxxx-xxxx-xxxx-b5b4b8a97604/brands
The final piece of information needed to access the API is the access token, prefixed with Bearer and provided in the Authorization header.
Use refresh tokens
You can use a refresh token to get a new access token after the access token expires. Depending on account and system security policies, refresh tokens may have a longer lifetime than access tokens. Refresh tokens usually do not require the account user to log in again.
To get a new access token, use the refresh token as you would an authorization code, but with a grant_type value of refresh_token and a refresh_token parameter that holds the contents of the refresh token.
The following table describes the elements of the request syntax.
Refresh tokens may be used for a variable period of time (that partially depends on business needs and may change at any time, but typically about 30 days) after the first authentication. When your application uses the refresh token to authenticate, it will be issued a new refresh token.
- If you have obtained the
extendedscope, a new refresh token is issued with a full lifetime (typically 30 days). It is possible for a user to remain logged in indefinitely by requesting theextendedscope and continually refreshing its access token. - If you do not have the
extendedscope, a new refresh token is issued that has the same expiration date as the original token (typically 30 days from first login). - If you receive any errors during the refresh operation, your integration should prompt the user to log in again to obtain a new access and refresh token.
Instead of waiting for an access token to expire, Docusign recommends that you refresh the access token when it is close to expiring (within 30 minutes, for example). When you first get the access token, use the expires_in value to calculate an expiration time. Store this expiration time in the user’s session.
Confidential Authorization Code Grant with SDKs
Instead of getting the access token manually using Confidential Authorization Code Grant, you can implement it by calling specific methods within the Docusign SDKs. The SDKs provide the getAuthorizationUri, generateAccessToken, and getUserInfo methods for automating Confidential Authorization Code Grant authentication. You can see these method definitions in the ApiClient class. See the language-specific SDK authentication page for details.
The getAuthorizationUri method is passed your app’s integration key, requested scopes, the redirect URI to which the user and the authorization code will be directed, the response type (value of code), and an optional state value.
The generateAccessToken method is passed your app’s integration key, client secret key, and authorization code. The method exchanges the authorization code for an access token and returns an access token.
The getUserInfo method is passed an access token and returns the owning user’s information, including the base URI that is needed to construct the paths to make other Docusign API calls.
Optional PKCE code challenge
You can use an additional code challenge, Proof Key for Code Exchange (PKCE), to ensure that the app that finishes the flow is the one that started it.
Generate code challenge values
To use the optional PKCE code challenge, before starting the standard confidential ACG flow and requesting an authorization code, first create a pair of code challenge values:
- Generate a cryptographically random string to use as the
code_verifier. - Hash the string you generated with the SHA256 algorithm using a standard cryptography library or tool, then base-64 URL encode it. The resulting value is the
code_challenge.
Note: As a best practice for generating cryptographically random strings:
- For C#, use System.Security.Cryptography.RNGCryptoServiceProvider.
- For Java, use java.security.SecureRandom .
- For Node.js, use the built-in crypto package. randomBytes has synchronous and asynchronous forms.
Add a code challenge to the authorization code request
After you have generated the code challenge values, you can make the authorization code request, including two additional parameters:
- The
code_challengefrom the previous step. - A
code_challenge_methodfield indicating the type of encryption that was used to create the code challenge. The only supported value is s256.
The accompanying URI syntax and Sample URI show how these values map to the sections of the URI.
Obtain the access token
Finally, when you make the API call to obtain the access token, you must validate your identity by supplying the code_verifier values along with this request. Docusign will hash the provided code_verifier and compare the result to the code_challenge from the initial authorization request. If the values are equal, your access token will be returned in the response.
Troubleshoot errors
refresh_token_mismatch
Indicates that the user’s password has changed and their refresh token has been revoked as a consequence. In this case, go through the flow again to get a new access token.
expired_client_token
Indicates that the refresh token has expired. In this case, go through the flow again to get a new access token.
user_does_not_belong_to_specified_account
Typically indicates that there is a mismatch between the authenticated user and the account ID provided in an API call, but can also be generated when the integration targets the wrong server for the user’s account.
BadRequest
Make sure that your application is attempting to connect to the correct authentication URI.
- For the developer environment, the URI is from the
https://account-d.docusign.com/oauthdomain. - For the production environment, the URI is from the
https://account.docusign.com/oauthdomain.
Client ID is disabled
Indicates that your app has been set as disabled. Enable your app, then try again.
Consent_Required
Indicates that the user has not consented to allow your application to make calls on their behalf or you have not requested a scope that is required for the operation.
If the user has supplied consent and you are still receiving this error, there may have been something wrong with the URI being used, or you may be lacking a required scope. Double check to make sure the integration key has not been cut off and that you have all required scopes. Also can be generated when
- You have not requested a scope that is required for the operation.
- You are attempting to grant admin consent but have not claimed a domain for your organization, or because you are missing a required organization entitlement. If you suspect this might be the cause of your error, please open a support case.
- You attempt to grant consent as the wrong user. To ensure that you are logging in as the correct user, add
&prompt=loginto your consent URI.
Invalid authentication request: The response type is not supported
Indicates that the application is not configured to use Authorization Code Grant or the response type specified in the authorization code request is not set to code. Ensure that the value of the response_type header is code.
To change the Authentication setting:
- Open the Apps and Keys page for your developer account.
- Under Apps and Integration Keys, choose the Integration Key to use, then select Actions, then Edit.
- Select Authorization Code Grant.
Invalid Grant
Indicates that the supplied authorization code is incomplete or expired. Ensure that there are no extra spaces on the start and end portions of the string, and that no characters have been truncated. If you used the state parameter, make sure that you’ve removed it from the end of the returned code value.
If you encounter this error repeatedly and/or after verifying that all parameters are correct, ask the user to log in again.
Invalid RedirectUri
Indicates that the redirect URI specified for authentication does not match any of the redirect URIs defined for the integration key. The redirect URI strings must match exactly, including space and slash characters.
Invalid user site ID
Indicates that the app called a site other than the user’s home site. Make sure that you are using the same site and domain to provide the token as those that you originally acquired it from.
Issuer not found
Indicates that the user is not present in the domain or environment (developer or production) used for the authentication flow. Ensure that you have specified the right domain and environment.
Page cannot be displayed after requesting the code
Indicates that the redirect URI is not set to a valid web page.
Refresh token mismatch
Indicates that the customer’s password expired or was changed since the refresh token was generated. You may need to obtain a new access token.
Token type mismatch
Indicates that your app has supplied the wrong type of token for a step in the authorization flow. For example, attempting to use a refresh token as an access token will result in this error. Make sure that your app is supplying the correct type of token for its step in the authorization flow.
User not found
Indicates that the specified user does not exist. Make sure that the user is a member of your app’s organization.
TOKENREQUEST_PKCE_MISSING_CODE_CHALLENGE_PARAMETERS
This error is generated when you provide a code challenge in an authorization code request but fail to include that challenge again when you try to exchange the authorization code for an access token.
If you provide PKCE code challenge values when requesting an authorization code, you must also provide the code challenge and verifier when exchanging that authorization code for an access token.
TOKENREQUEST_PKCE_MISSING_CODE_VERIFIER
This error is generated when you provide a code challenge in an authorization code request but fail to include the code verifier when you try to exchange the authorization code for an access token.
If you provide PKCE code challenge values when requesting an authorization code, you must also provide the code challenge and verifier when exchanging that authorization code for an access token.
TOKENREQUEST_PKCE_NOT_INCLUDED_WHEN_REQUIRED
This error is generated when the PKCE authentication challenge has been set to be required, but you fail to provide the code challenge or code challenge method when you request an authorization code.
If PKCE is required for your app, you must provide both a code challenge and code challenge method when requesting an access token.
TOKENREQUEST_PKCE_UNEXPECTED_CODE_CHALLENGE_METHOD
Indicates that the provided code challenge method is invalid. The value of code_challenge_method should be sha256.
Next steps
- See Authorization Code Grant for context about this authentication flow.
- See Choose an OAuth type for a breakdown of the advantages and disadvantages of each OAuth option, including Confidential Authorization Code Grant.
- Watch this OAuth Authorization Code Grant webinar for an in-depth walkthrough of when to use Confidential Authorization Code Grant, how it works, and how to get an access token.