> You are reading the Docusign Developer Documentation. For clean Markdown of any page, append .md to the page URL.
>
> Documentation indexes by section:
> - APIs and SDKs: https://docusign.docs.buildwithfern.com/docs/llms.txt
> - Platform 101: https://docusign.docs.buildwithfern.com/platform/llms.txt
> - Extension Apps: https://docusign.docs.buildwithfern.com/extension-apps/llms.txt
> - Docusign CLI: https://docusign.docs.buildwithfern.com/docusign-cli/llms.txt
>
> Authentication (OAuth, JWT Grant, M2M): https://docusign.docs.buildwithfern.com/platform/auth
> Webhooks and Connect: https://docusign.docs.buildwithfern.com/platform/webhooks
>
> OpenAPI specifications: https://docusign.docs.buildwithfern.com/openapi.json
> MCP server: https://docusign.docs.buildwithfern.com/_mcp/server

# How to obtain consent

> Discover how to obtain consent using Docusign OAuth in your application using the Apex Toolkit.

This topic demonstrates how to obtain consent from individual users using Docusign OAuth in your application using the Apex Toolkit. To learn how to obtain admin consent for your organization, see Step 3 of [How to authenticate](/docs/salesforce/how-to/authenticate#step-3-obtain-user-consent).

## Before you begin

* Install the [Docusign eSignature for Salesforce](https://appexchange.salesforce.com/appxListingDetail?listingId=a0N30000001taX4EAI) managed package. You must install or upgrade to version 2.2 or later.
* Navigate to the Docusign Setup tab and complete the login step.
* Use the code provided in your application's Apex classes as a basis for your implementation of obtaining user consent.

## Step 1. Detect user consent status

When a user invokes a method that requires a Docusign API callout, the Apex Toolkit will verify that user has a valid access token for the request. If the user does not have a valid token, the Apex Toolkit will attempt to exchange a [JWT](/platform/auth/jwt-get-token) for an access token. If this call fails because the user has not granted their consent, the Apex Toolkit throws a [dfsle.APIException](/docs/salesforce/apex-toolkit-reference/apiexception.html) with the error code `dsfle.APIErrorCode.CONSENT_REQUIRED`.

**`Apex`**

```java title="Apex"
try {
    dfsle.EnvelopeService.sendEnvelope(envelope, true);
} catch (dfsle.APIException ex) {
    if (ex.error.code == dfsle.APIErrorCode.CONSENT_REQUIRED) {
        // user is a valid member of the DocuSign account, but has not granted consent to this application
    } else {
        // handle other errors
    }
}
```

## Step 2. Request a login URL

After detecting the consent requirement, call the [dfsle.AuthService.getLoginUrl](/docs/salesforce/apex-toolkit-reference/authservice.html) method. This takes a single argument: the path to a page you want to redirect users to after completing the consent flow. Any query string parameters specified will be passed through as-is.

Your redirect page must reside on your current Salesforce org; no external redirects are allowed. For example, `/apex/myPage?myState=whatever` is a valid redirect while `https://example.com/myPage?myState=whatever` is invalid. The Apex Toolkit will not throw an exception in the latter case but will prepend a forward slash to your redirect URL so it will be treated as a relative path on the current Salesforce host: `/https://example.com/myPage?myState=whatever`.

The generated login URL is valid only once for the requesting user.

**`Apex`**

```java title="Apex"
Url loginUrl = dfsle.AuthService.getLoginUrl('/apex/myPage?myState=whatever');
```

## Step 3. Open the login URL

Once you have the Docusign login URL, redirect your user to it. Bear in mind that you cannot iframe this URL: it must either be a full-page redirect or opened in a new window or tab.

To open the login URL in **a new window or tab** in either Lightning or Visualforce:

**`JavaScript`**

```javascript title="JavaScript"
window.open(loginUrl, '_blank');
```

To open the login URL in **the current window** in Lightning or Visualforce:

**`Lightning`**

```java title="Lightning"
var navEvent = $A.get('e.force:navigateToURL');
navEvent.setParam('url', loginUrl);
navEvent.fire();
```

**`Visualforce`**

```html title="Visualforce"
window.location.assign(loginUrl);
```

### Salesforce HTML escaping

By default Salesforce HTML-encodes `@RemoteAction` and `@AuraEnabled` function output. This will cause an error if you blindly redirect to the generated login URL in your Visualforce page or Lightning component: "Invalid authentication request: The response type is not supported."

To prevent this error you can HTML-decode the URL at the time it is used with `HTMLDECODE` or your own JavaScript function. If invoking a `@RemoteAction` method, you can prevent result escaping by specifying `{escape: false}` with `Visualforce.remoting.Manager.invokeAction`. For example:

**`JavaScript`**

```javascript title="JavaScript"
Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.MyController.getLoginUrl}', function (loginUrl, event) {
  if (event && event.status) {
    window.open(loginUrl, '_blank');
  }
}, {escape: false});
```

## Step 4. Check the login result

Once the user has logged into Docusign and completed the consent flow, they will be redirected to your page. The Apex Toolkit adds query string parameters describing the result of this flow:

* `dfsle__status`: Either `Success` or `Failure`.
* `dfsle__message`: Additional details in case of failures.

**`HTML`**

```html title="HTML"
<aura:component implements="lightning:isUrlAddressable">
    <aura:handler name="init" value="{!this}" action="{!c.onInit}"/>
</aura:component>
```

You can redirect to a URL-addressable Lightning component with any of these methods, shown in the sample code:

* JavaScript controller
* Visualforce page
* Apex controller

**`JavaScript`**

```javascript title="JavaScript"
({
  onInit: function (component, event, helper) {
    var status = component.get('v.pageReference.state.dfsle__status');
    var message = component.get('v.pageReference.state.dfsle__message');
    if (status === 'Success') {
      // continue original transaction
    } else {
      // display message
    }
  }
});
```

**`Visualforce`**

```html title="Visualforce"
<apex:page controller="MyController" action="{!c.verifyVisualforceResult}"/>
```

**`Apex`**

```java title="Apex"
public with sharing class MyController {

    public PageReference verifyVisualforceResult() {
        String status = ApexPages.currentPage().getParameters().get('dfsle__status');
        String message = ApexPages.currentPage().getParameters().get('dfsle__message');
        if (status == 'Success') {
            // continue original transaction
        } else {
            // display message
        }
    }
}
```

## Step 5. Continue original transaction

After the user has granted consent, they are now able to invoke other Apex Toolkit functions without further interactions with the Docusign authentication service.

Users have the ability to revoke their consent at any time, so your application must be prepared to display appropriate messaging and send them through the consent flow again.