> 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 share access to a Docusign envelope inbox

> This topic demonstrates how to share envelope inbox access with another user and view an envelope using the SHARED ACCESS view in the Docusign UI.

eSignature REST API 2.1 only

This topic demonstrates how to share envelope inbox access with another user and view an envelope using the **SHARED ACCESS** view in the Docusign UI. The Shared Access feature enables a user (the *principal*) to grant another user (the *agent*) access to the principal’s envelopes.

**Important**: There must be envelopes in the principal’s inbox to complete this how-to. See  [How to request a signature by email](/docs/esign-rest-api/how-to/request-signature-email-remote) to learn more about creating an envelope.

See [Shared Access](/docs/esign-rest-api/esign101/concepts/envelopes/share-access-to-mailbox-or-envelopes) for details on the feature and the list of supported envelope actions.

> **Note**
>
> Run this code example from our [Quickstart](/docs/esign-rest-api/quickstart) or launcher projects: [Bash](https://github.com/docusign/code-examples-bash), [C#](https://github.com/docusign/code-examples-csharp), [Java](https://github.com/docusign/code-examples-java), [Node.js](https://github.com/docusign/code-examples-node), [PHP](https://github.com/docusign/code-examples-php), [PowerShell](https://github.com/docusign/code-examples-powershell), [Python](https://github.com/docusign/code-examples-python), or [Ruby](https://github.com/docusign/code-examples-ruby).

## Required data

Running the code in this how-to requires this data:

| Data element               | Description                                                                                                                                                                                                                                                                                                            |
| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| \{ACTIVATION}              | A string value, 50 characters or less, that you provide to the agent to activate their account. This string must not contain the symbols \<, >, &, and #.                                                                                                                                                              |
| \{AGENT_EMAIL}             | A string value for the email address of the agent.                                                                                                                                                                                                                                                                     |
| \{AGENT_NAME}              | A string value for the full name of the agent.                                                                                                                                                                                                                                                                         |
| \{AGENT_USER_ID}           | A [GUID](http://guid.one/) value that identifies the user. This value is automatically generated by Docusign. Copy the value from the **User ID** field on the [Apps and Keys](https://admindemo.docusign.com/authenticate?goTo=appsAndKeys) page.                                                                     |
| \{API_ACCOUNT_ID}          | A [GUID](http://guid.one/) value that identifies your account. This value is automatically generated by Docusign for any account you create. Copy the value from the **API Account ID** field on the [Apps and Keys](https://admindemo.docusign.com/authenticate?goTo=appsAndKeys) page.                               |
| \{BASE_PATH}               | A string value that forms the root of the URL required to make API calls. The base path value in the example code is set to target the developer environment at https\://\<domain>/restapi Where \<domain> is demo.docusign.net for the developer environment and is the result of the GetUserInfo call in production. |
| \{IMPERSONATION_USER_GUID} | A [GUID](http://guid.one/) value that identifies the user. This value is automatically generated by Docusign. Copy the value from the **User ID** field on the [Apps and Keys](https://admindemo.docusign.com/authenticate?goTo=appsAndKeys) page.                                                                     |

## Step 1. Obtain your OAuth token

To make the API calls shown in this how-to, you need a valid OAuth access token. Docusign supports access tokens for three different recommended OAuth grant types: Public Authorization Code Grant, Confidential Authorization Code Grant, and JSON Web Token (JWT) Grant. Choose the OAuth grant type appropriate for your scenario.

> **Note**
>
> See [Confidential Authorization Code Grant](/platform/auth/authcode#confidential-authorization-code-grant) for guidance on your options to get an Confidential Authorization Code Grant  OAuth token.

![Three icons that represent the three methods a user can use to obtain an OAuth token: JSON Web Token (JWT), Public Authorization Code Grant (ACG), and Confidential Authorization Code grant](/_fern-files/_img/64f473773042ee439449a096bf7673292b1585b86a4ccc55f82ba0dda41f61a1.webp)

## Step 2. Construct your API headers

After you have a valid OAuth access token, you are ready to construct the API headers that you will pass to the API call. Construct your headers like this, but make sure to substitute your valid OAuth access token for \{ACCESS_TOKEN}.

**`Bash`**

```bash title="Bash"
declare -a Headers=('--header' "Authorization: Bearer ${ACCESS_TOKEN}"
    '--header' "Accept: application/json"
    '--header' "Content-Type: application/json")
```

**`C#`**

```csharp title="C#"
var docuSignClient = new DocuSignClient(basePath);
docuSignClient.Configuration.DefaultHeader.Add("Authorization", "Bearer " + accessToken);
var usersApi = new UsersApi(docuSignClient);
```

**`Java`**

```java title="Java"
ApiClient apiClient = new ApiClient(basePath);
apiClient.addDefaultHeader(HttpHeaders.AUTHORIZATION, BEARER_AUTHENTICATION + userAccessToken);
```

**`Node.js`**

```javascript title="Node.js"
const dsApiClient = new docusign.ApiClient();
dsApiClient.setBasePath(args.basePath);
dsApiClient.addDefaultHeader('Authorization', 'Bearer ' + args.accessToken);
```

**`PHP`**

```php title="PHP"
$config = new Configuration();
$config->setHost($basePath);
$config->addDefaultHeader('Authorization', 'Bearer ' . $accessToken);

$oauth = new OAuth();
$oauth->setOAuthBasePath(self::BASEPATH);

$apiClient = new ApiClient($config, $oauth);
```

**`PowerShell`**

```text title="PowerShell"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.add("Authorization", "Bearer $accessToken")
$headers.add("Content-Type", "application/json")
```

**`Python`**

```python title="Python"
api_client = create_api_client(base_path=args["base_path"], access_token=args["access_token"])
```

**`Ruby`**

```ruby title="Ruby"
configuration = DocuSign_eSign::Configuration.new
configuration.host = args[:base_path]
api_client = DocuSign_eSign::ApiClient.new configuration
api_client.default_headers['Authorization'] = "Bearer #{args[:access_token]}"
```

## Step 3. Construct the request body to create an agent and call the API

> **Note**
>
> To share access to the principal’s envelopes with an agent, there must be at least two users in the principal’s account. This step creates a new agent with whom the principal’s envelope inbox will be shared. If there is already a second user in the principal’s account, you can skip this step and instead record the second user’s user ID to use in the next step.

First, create the request body for the API call to create an agent. Set the `userName` and `email` fields to the name and email address associated with the agent. Set the `activationAccessCode` to a string that the agent will use to activate their account. Make a POST request to the [Users:create](/docs/esign-rest-api/reference/users/users/create) endpoint and include the request body to create the agent. Then, extract the agent’s `userId` from the response as \{AGENT_USER_ID}. You will use it again in Step 4.

**`Bash`**

```bash title="Bash"
printf \
'{
  "newUsers": [
    {
      "activationAccessCode": "'"${ACTIVATION}"'",
      "userName": "'"${AGENT_NAME}"'",
      "email": "'"${AGENT_EMAIL}"'"
    }
  ]
}' >> $request_data

Status=$(curl --request POST ${base_path}/v2.1/accounts/${ACCOUNT_ID}/users \
"${Headers[@]}" \
--data-binary @${request_data} \
--output ${response})

echo ""
echo "Response: "
cat $response
echo ""

AGENT_USER_ID=`cat $response | grep userId | sed 's/.*\"userId\":\"//' | sed 's/\",.*//'`
```

**`C#`**

```csharp title="C#"
var newUser = new NewUsersDefinition
{
    NewUsers = new List<UserInformation>
    {
        new UserInformation(activationCode, Email: agentEmail, UserName: agentName),
    },
};

var userSummary = usersApi.CreateWithHttpInfo(accountId, newUser);
userSummary.Headers.TryGetValue("X-RateLimit-Remaining", out string remaining);
userSummary.Headers.TryGetValue("X-RateLimit-Reset", out string reset);

if (reset != null && remaining != null)
{
    DateTime resetDate = DateTimeOffset.FromUnixTimeSeconds(long.Parse(reset)).UtcDateTime;
    Console.WriteLine("API calls remaining: " + remaining);
    Console.WriteLine("Next Reset: " + resetDate);
}
```

**`Java`**

```java title="Java"
UserInformation user = new UserInformation();
user.email(agentEmail);
user.userName(agentName);
user.activationAccessCode(activation);

NewUsersDefinition usersDefinition = new NewUsersDefinition();
usersDefinition.addNewUsersItem(user);

var createUser = usersApi.createWithHttpInfo(accountId, usersDefinition);
Map<String, java.util.List<String>> headers = createUser.getHeaders();
java.util.List<String> remaining = headers.get("X-RateLimit-Remaining");
java.util.List<String> reset = headers.get("X-RateLimit-Reset");

if (remaining != null & reset != null) {
    Instant resetInstant = Instant.ofEpochSecond(Long.parseLong(reset.get(0)));
    System.out.println("API calls remaining: " + remaining);
    System.out.println("Next Reset: " + resetInstant);
}
return createUser.getData();
```

**`Node.js`**

```javascript title="Node.js"
const createNewUserDefinition = (args) => {
  const newUsersDefinition = docusign.NewUsersDefinition.constructFromObject({
    newUsers: [
      docusign.UserInformation.constructFromObject({
        activationAccessCode: args.activation,
        userName: args.userName,
        email: args.email,
      }),
    ],
  });

  return newUsersDefinition;
};
```

**`PHP`**

```php title="PHP"
$newUser = new NewUsersDefinition();
$newUser->setNewUsers([
    new UserInformation([
        "activation_access_code" => $activationCode,
        "email" => $agentEmail,
        "user_name" => $agentName])
]);

$response = $usersApi->createWithHttpInfo($accountId, $newUser);

$remaining = $response[2]['X-RateLimit-Remaining'] ?? null;
$reset = $response[2]['X-RateLimit-Reset'] ?? null;

if ($remaining !== null && $reset !== null) {
    $resetInstant = (new DateTime())->setTimestamp((int)$reset);
    error_log("API calls remaining: $remaining");
    error_log("Next Reset: " . $resetInstant->format(\DateTime::ATOM));
}
return $response[0];
```

**`PowerShell`**

```text title="PowerShell"
try {
    # Check, if the agent already exists
    Invoke-RestMethod `
        -Uri "${apiUri}/v2.1/accounts/${accountId}/users?email=${agentEmail}&status=Active" `
        -Method 'GET' `
        -Headers @{
            'Authorization' = "Bearer $accessToken";
            'Content-Type'  = "application/json";
        } `
        -OutFile $response

    Write-Output ""
    Write-Output "Response:"
    Write-Output ""
    Get-Content $response

    $agentUserId = $(Get-Content $response | ConvertFrom-Json).users.userId
} catch {
    # Create a new agent in the account
    @{
        newUsers = @(
            @{
                activationAccessCode = $activation;
                userName = $agentName;
                email = $agentEmail;
            };
        );
    } | ConvertTo-Json -Depth 32 > $requestData

    Invoke-RestMethod `
        -Uri "${apiUri}/v2.1/accounts/${accountId}/users" `
        -Method 'POST' `
        -Headers @{
        'Authorization' = "Bearer $accessToken";
        'Content-Type'  = "application/json";
    } `
        -InFile (Resolve-Path $requestData).Path `
        -OutFile $response

    Write-Output ""
    Write-Output "Response:"
    Write-Output ""
    Get-Content $response

    $agentUserId = $(Get-Content $response | ConvertFrom-Json).newUsers.userId
```

**`Python`**

```python title="Python"
users_api = UsersApi(api_client)
(new_users, status, headers) = users_api.create_with_http_info(args["account_id"], new_users_definition=cls.new_users_definition(args))

remaining = headers.get("X-RateLimit-Remaining")
reset = headers.get("X-RateLimit-Reset")

if remaining is not None and reset is not None:
    reset_date = dt.fromtimestamp(int(reset), tz=timezone.utc)
    print(f"API calls remaining: {remaining}")
    print(f"Next Reset: {reset_date}")

return new_users.new_users[0]
    @classmethod
    def new_users_definition(cls, args):
agent = UserInformation(
    user_name=args["user_name"],
    email=args["email"],
    activation_access_code=args["activation"]
)
return NewUsersDefinition(new_users=[agent])
```

**`Ruby`**

```ruby title="Ruby"
users_api = DocuSign_eSign::UsersApi.new api_client
new_users, _status, headers = users_api.create_with_http_info args[:account_id], new_users_definition(args)

remaining = headers['X-RateLimit-Remaining']
reset = headers['X-RateLimit-Reset']

if remaining && reset
  reset_date = Time.at(reset.to_i).utc
  puts "API calls remaining: #{remaining}"
  puts "Next Reset: #{reset_date}"
end

new_users.new_users[0]
  def new_users_definition(args)
agent = DocuSign_eSign::UserInformation.new(
  userName: args[:user_name],
  email: args[:email],
  activationAccessCode: args[:activation]
)
DocuSign_eSign::NewUsersDefinition.new(newUsers: [agent])
  end
```

## Step 4. Construct the request body to grant authorization and call the API

> **Note**
>
> This step grants shared access to the principal’s Docusign envelope inbox to the agent created in the previous step. If you already have a second user with whom you’d like to share access, you can provide their user ID in the `agentUser` JSON.

Now that you have created an agent, you need to authorize the agent to manage envelopes in the principal’s inbox. Set the `userId` field to the one associated with the agent and set the permission to `manage`. Make a POST request to the Users:authorization endpoint and include the request body to authorize the agent to manage the principal’s envelopes. Use the principal’s user ID as \{IMPERSONATION_USER_GUID} and the principal’s API account ID as \{ACCOUNT_ID} in the call.

**`Bash`**

```bash title="Bash"
printf \
'{
    "agentUser":
        {
            "userId": "'"${AGENT_USER_ID}"'",
            "accountId": "'"${ACCOUNT_ID}"'"
        },
    "permission": "manage"
}' >> $request_data

Status=$(curl --request POST ${base_path}/v2.1/accounts/${ACCOUNT_ID}/users/${IMPERSONATION_USER_GUID}/authorization \
"${Headers[@]}" \
--data-binary @${request_data} \
--output ${response})
```

**`C#`**

```csharp title="C#"
var docuSignClient = new DocuSignClient(basePath);
docuSignClient.Configuration.DefaultHeader.Add("Authorization", "Bearer " + accessToken);
var accountApi = new AccountsApi(docuSignClient);

var managePermission = "manage";
var options = new AccountsApi.GetAgentUserAuthorizationsOptions
{
    permissions = managePermission,
};
var userAuthorizations = accountApi.GetAgentUserAuthorizationsWithHttpInfo(accountId, agentUserId, options);
userAuthorizations.Headers.TryGetValue("X-RateLimit-Remaining", out string remaining);
userAuthorizations.Headers.TryGetValue("X-RateLimit-Reset", out string reset);

if (reset != null && remaining != null)
{
    DateTime resetDate = DateTimeOffset.FromUnixTimeSeconds(long.Parse(reset)).UtcDateTime;
    Console.WriteLine("API calls remaining: " + remaining);
    Console.WriteLine("Next Reset: " + resetDate);
}

if (userAuthorizations.Data.Authorizations == null || userAuthorizations.Data.Authorizations.Count == 0)
{
    var authRequest = new UserAuthorizationCreateRequest(
        Permission: managePermission,
        AgentUser: new AuthorizationUser(AccountId: accountId, UserId: agentUserId));

    var createUserAuthorization = accountApi.CreateUserAuthorizationWithHttpInfo(accountId, userId, authRequest);
    createUserAuthorization.Headers.TryGetValue("X-RateLimit-Remaining", out remaining);
    createUserAuthorization.Headers.TryGetValue("X-RateLimit-Reset", out reset);

    if (reset != null && remaining != null)
    {
        DateTime resetDateTime = DateTimeOffset.FromUnixTimeSeconds(long.Parse(reset)).UtcDateTime;
        Console.WriteLine("API calls remaining: " + remaining);
        Console.WriteLine("Next Reset: " + resetDateTime);
    }
}
```

**`Java`**

```java title="Java"
AuthorizationUser user = new AuthorizationUser();
user.userId(createdUserId);
user.accountId(accountId);

UserAuthorizationCreateRequest userAuthorizationCreateRequest = new UserAuthorizationCreateRequest();
userAuthorizationCreateRequest.agentUser(user);
userAuthorizationCreateRequest.permission(MANAGE);

var createAuthorization = accountsApi.createUserAuthorizationWithHttpInfo(accountId, userId,
        userAuthorizationCreateRequest);
headers = createAuthorization.getHeaders();
remaining = headers.get("X-RateLimit-Remaining");
reset = headers.get("X-RateLimit-Reset");

if (remaining != null & reset != null) {
    Instant resetInstant = Instant.ofEpochSecond(Long.parseLong(reset.get(0)));
    System.out.println("API calls remaining: " + remaining);
    System.out.println("Next Reset: " + resetInstant);
}
```

**`Node.js`**

```javascript title="Node.js"
const createAuthorization = async (args) => {
  const dsApiClient = new docusign.ApiClient();
  dsApiClient.setBasePath(args.basePath);
  dsApiClient.addDefaultHeader('Authorization', 'Bearer ' + args.accessToken);
  const accountsApi = new docusign.AccountsApi(dsApiClient);

  // check if authorization with manage permission already exists
  const authorizations = await accountsApi.getAgentUserAuthorizations(args.accountId, args.agentUserId, { permissions: 'manage' }, (error, data, response) => {
      const headers = response?.headers;

      const remaining = headers?.['x-ratelimit-remaining'];
      const reset = headers?.['x-ratelimit-reset'];

      if (remaining && reset) {
        const resetInstant = new Date(Number(reset) * 1000);

        console.log(`API calls remaining: ${remaining}`);
        console.log(`Next Reset: ${resetInstant.toISOString()}`);
      }
  });
  if (authorizations.data.resultSetSize > 0) {
    return;
  }

  // create authorization
  const agentData = createAuthorizationRequest(args.agentUserId, args);
  await accountsApi.createUserAuthorization(args.accountId, args.userId, { userAuthorizationCreateRequest: agentData }, (error, data, response) => {
      const headers = response?.headers;

      const remaining = headers?.['x-ratelimit-remaining'];
      const reset = headers?.['x-ratelimit-reset'];

      if (remaining && reset) {
        const resetInstant = new Date(Number(reset) * 1000);

        console.log(`API calls remaining: ${remaining}`);
        console.log(`Next Reset: ${resetInstant.toISOString()}`);
      }
  });
};
```

**`PHP`**

```php title="PHP"
public static function createUserAuthorization(
    string $basePath,
    string $accessToken,
    string $accountId,
    string $userId,
    string $agentUserId
): void {
    $config = new Configuration();
    $config->setHost($basePath);
    $config->addDefaultHeader('Authorization', 'Bearer ' . $accessToken);

    $oauth = new OAuth();
    $oauth->setOAuthBasePath(self::BASEPATH);

    $apiClient = new ApiClient($config, $oauth);
    $accountsApi = new AccountsApi($apiClient);

    $managePermission = "manage";

    $options = new AccountsApi\GetAgentUserAuthorizationsOptions();
    $options->setPermissions($managePermission);
    $userAuthorizations = $accountsApi->getAgentUserAuthorizationsWithHttpInfo($accountId, $userId);

    $remaining = $userAuthorizations[2]['X-RateLimit-Remaining'] ?? null;
    $reset = $userAuthorizations[2]['X-RateLimit-Reset'] ?? null;

    if ($remaining !== null && $reset !== null) {
        $resetInstant = (new DateTime())->setTimestamp((int)$reset);
        error_log("API calls remaining: $remaining");
        error_log("Next Reset: " . $resetInstant->format(\DateTime::ATOM));
    }

    if ($userAuthorizations[0]->getAuthorizations() === null) {
        $authRequest = new UserAuthorizationCreateRequest();
        $authRequest->setPermission($managePermission);
        $authRequest->setAgentUser(new AuthorizationUser([
            'account_id' => $accountId,
            'user_id' => $agentUserId
         ]));

        $response = $accountsApi->createUserAuthorizationWithHttpInfo($accountId, $userId, $authRequest);

        $remaining = $response[2]['X-RateLimit-Remaining'] ?? null;
        $reset = $response[2]['X-RateLimit-Reset'] ?? null;

        if ($remaining !== null && $reset !== null) {
            $resetInstant = (new DateTime())->setTimestamp((int)$reset);
            error_log("API calls remaining: $remaining");
            error_log("Next Reset: " . $resetInstant->format(\DateTime::ATOM));
        }
    }
}
```

**`PowerShell`**

```text title="PowerShell"
$isUserActivated = 0;

do {
    try {
        # Check, if authorization exists
        Invoke-RestMethod `
            -Uri "${apiUri}/v2.1/accounts/${accountId}/users/${agentUserId}/authorizations/agent?permissions=manage" `
            -Method 'GET' `
            -Headers @{
                'Authorization' = "Bearer $accessToken";
                'Content-Type'  = "application/json";
            } `
            -OutFile $response

        if ([string]::IsNullOrEmpty($(Get-Content $response | ConvertFrom-Json).authorizations)) {
            # Sharing the envelope with the agent
            $body = @"
            {
                "agentUser":
                    {
                        "userId": "${agentUserId}",
                        "accountId": "${accountId}"
                    },
                "permission": "manage"
            }
"@

            Write-Output ""
            $uri = "${apiUri}/v2.1/accounts/${accountId}/users/${userId}/authorization"

            $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
            $headers.add("Authorization", "Bearer $accessToken")
            $headers.add("Content-Type", "application/json")

            Invoke-WebRequest -uri $uri -headers $headers -body $body -method POST -UseBasicParsing -OutFile $response

            Write-Output "Response:"
            Write-Output "$(Get-Content -Raw $response)"
        }

        $isUserActivated = 1;
```

**`Python`**

```python title="Python"
@classmethod
def create_authorization(cls, args):
    api_client = create_api_client(base_path=args["base_path"], access_token=args["access_token"])
    accounts_api = AccountsApi(api_client)

    # check if authorization with manage permission already exists
    (authorizations, status, headers) = accounts_api.get_agent_user_authorizations_with_http_info(
        args["account_id"],
        args["agent_user_id"],
        permissions="manage"
    )

    remaining = headers.get("X-RateLimit-Remaining")
    reset = headers.get("X-RateLimit-Reset")

    if remaining is not None and reset is not None:
        reset_date = dt.fromtimestamp(int(reset), tz=timezone.utc)
        print(f"API calls remaining: {remaining}")
        print(f"Next Reset: {reset_date}")

    if int(authorizations.result_set_size) > 0:
        return

    # create authorization
    (authorization, status, headers) = accounts_api.create_user_authorization_with_http_info(
        args["account_id"],
        args["user_id"],
        user_authorization_create_request=cls.user_authorization_request(args)
    )

    remaining = headers.get("X-RateLimit-Remaining")
    reset = headers.get("X-RateLimit-Reset")

    if remaining is not None and reset is not None:
        reset_date = dt.fromtimestamp(int(reset), tz=timezone.utc)
        print(f"API calls remaining: {remaining}")
        print(f"Next Reset: {reset_date}")
```

**`Ruby`**

```ruby title="Ruby"
accounts_api = DocuSign_eSign::AccountsApi.new api_client

# Check if authorization with manage permission already exists
options = DocuSign_eSign::GetAgentUserAuthorizationsOptions.new
options.permissions = 'manage'

authorizations, _status, headers = accounts_api.get_agent_user_authorizations_with_http_info(args[:account_id], args[:agent_user_id], options)

remaining = headers['X-RateLimit-Remaining']
reset = headers['X-RateLimit-Reset']

if remaining && reset
  reset_date = Time.at(reset.to_i).utc
  puts "API calls remaining: #{remaining}"
  puts "Next Reset: #{reset_date}"
end

return if authorizations.result_set_size.to_i.positive?

# Create authorization
_results, _status, headers = accounts_api.create_user_authorization_with_http_info(
  args[:account_id],
  args[:user_id],
  user_authorization_request(args)
)

remaining = headers['X-RateLimit-Remaining']
reset = headers['X-RateLimit-Reset']

return unless remaining && reset

reset_date = Time.at(reset.to_i).utc
puts "API calls remaining: #{remaining}"
puts "Next Reset: #{reset_date}"

  def user_authorization_request(args)
DocuSign_eSign::UserAuthorizationCreateRequest.new(
  agentUser: DocuSign_eSign::AuthorizationUser.new(
    accountId: args[:account_id],
    userId: args[:agent_user_id]
  ),
  permission: 'manage'
)
  end
```

## Expected response

Now that the agent has been authorized, the agent should be able to see the principal’s envelopes in their Shared Access UI. To verify that the principal’s envelopes can be viewed by the agent, log in to the agent’s Docusign developer account, then open the [Agreements tab](https://apps-d.docusign.com/send/documents)  in the eSignature UI.  Select **SHARED ACCESS** in the upper left, then select the principal’s account. The principal’s envelopes should be displayed in **Sent**.

![Viewing shared envelopes in the Sent folder](/_fern-files/_img/bebb0b56096921dfe9bc62b1692d7170261f0ddd5c721e1d3d19ea8833149655.webp)

## Step 5. Call the eSignature REST API as the agent

> **Note**
>
> The following API call will be made by the agent. Before making this API call, you need to authenticate as the agent.

After you have authenticated as the agent, confirm that the envelope inbox has been shared by calling the [Envelopes:listStatus](/docs/esign-rest-api/reference/envelopes/envelopes/liststatus) endpoint. Any API calls made on behalf of the principal need to include the `X-DocuSign-Act-On-Behalf` header and substitute the principal’s user ID for \{IMPERSONATION_USER_GUID}. Be sure to also substitute the API account ID of the agent for \{ACCOUNT_ID}.

> **Note**
>
> View the source code for this how-to on GitHub: [Bash](https://github.com/docusign/code-examples-bash/blob/master/examples/eSignature/eg043SharedAccess.sh), [C#](https://github.com/docusign/code-examples-csharp/blob/master/launcher-csharp/eSignature/Examples/SharedAccess.cs), [Java](https://github.com/docusign/code-examples-java/blob/master/src/main/java/com/docusign/controller/eSignature/services/SharedAccessService.java),  [Node.js](https://github.com/docusign/code-examples-node/blob/master/lib/eSignature/examples/sharedAccess.js), [PHP](https://github.com/docusign/code-examples-php/blob/master/src/Controllers/Examples/eSignature/EG043AuthRequest.php), [PowerShell](https://github.com/docusign/code-examples-powershell/blob/master/examples/eSignature/eg043SharedAccess.ps1), [Python](https://github.com/docusign/code-examples-python/blob/master/app/eSignature/examples/eg043_shared_access.py), or [Ruby](https://github.com/docusign/code-examples-ruby/blob/master/app/services/e_sign/eg043_shared_access_service.rb).

**`Bash`**

```bash title="Bash"
response=$(mktemp /tmp/response-bs.XXXXXX)

if date -v -10d &> /dev/null ; then
    # Mac
    from_date=`date -v -10d '+%Y-%m-%dT%H:%M:%S%z'`
else
    # Not a Mac
    from_date=`date --date='-10 days' '+%Y-%m-%dT%H:%M:%S%z'`

curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
     --header "X-DocuSign-Act-On-Behalf: ${IMPERSONATION_USER_GUID}" \
     --header "Content-Type: application/json" \
     --get \
     --output $response \
     --data-urlencode "from_date=${from_date}" \
     --request GET ${base_path}/v2.1/accounts/${ACCOUNT_ID}/envelopes/
```

**`C#`**

```csharp title="C#"
var docuSignClient = new DocuSignClient(basePath);
docuSignClient.Configuration.DefaultHeader.Add("Authorization", "Bearer " + accessToken);
docuSignClient.Configuration.DefaultHeader.Add("X-DocuSign-Act-On-Behalf", userId);

var envelopesApi = new EnvelopesApi(docuSignClient);

var date = DateTime.UtcNow.AddDays(-10).ToString("yyyy-MM-ddTHH:mmZ");
var option = new EnvelopesApi.ListStatusChangesOptions()
{
    fromDate = date,
};

var envelopes = envelopesApi.ListStatusChangesWithHttpInfo(accountId, option);
envelopes.Headers.TryGetValue("X-RateLimit-Remaining", out string remaining);
envelopes.Headers.TryGetValue("X-RateLimit-Reset", out string reset);

if (reset != null && remaining != null)
{
    DateTime resetDate = DateTimeOffset.FromUnixTimeSeconds(long.Parse(reset)).UtcDateTime;
    Console.WriteLine("API calls remaining: " + remaining);
    Console.WriteLine("Next Reset: " + resetDate);
}
```

**`Java`**

```java title="Java"
EnvelopesApi.ListStatusChangesOptions options = envelopesApi.new ListStatusChangesOptions();
LocalDate date = LocalDate.now().minusDays(FROM_DATE_OFFSET_DAYS);
options.setFromDate(DateUtils.DATE_WITH_SLASH.format(date));

var listStatusResponse = envelopesApi.listStatusChangesWithHttpInfo(accountId, options);
Map<String, java.util.List<String>> headers = listStatusResponse.getHeaders();
java.util.List<String> remaining = headers.get("X-RateLimit-Remaining");
java.util.List<String> reset = headers.get("X-RateLimit-Reset");

if (remaining != null & reset != null) {
    Instant resetInstant = Instant.ofEpochSecond(Long.parseLong(reset.get(0)));
    System.out.println("API calls remaining: " + remaining);
    System.out.println("Next Reset: " + resetInstant);
}
return listStatusResponse.getData();
```

**`Node.js`**

```javascript title="Node.js"
const getEnvelopes = async (args) => {
  const dsApiClient = new docusign.ApiClient();
  dsApiClient.setBasePath(args.basePath);
  dsApiClient.addDefaultHeader('Authorization', 'Bearer ' + args.accessToken);
  dsApiClient.addDefaultHeader('X-DocuSign-Act-On-Behalf', args.userId);
  const envelopesApi = new docusign.EnvelopesApi(dsApiClient);

  const options = { fromDate: moment().subtract(10, 'days').format() };
  response = await envelopesApi.listStatusChanges(args.accountId, options, (error, data, response) => {
      const headers = response?.headers;

      const remaining = headers?.['x-ratelimit-remaining'];
      const reset = headers?.['x-ratelimit-reset'];

      if (remaining && reset) {
        const resetInstant = new Date(Number(reset) * 1000);

        console.log(`API calls remaining: ${remaining}`);
        console.log(`Next Reset: ${resetInstant.toISOString()}`);
      }
  });
  return response.data;
};
```

**`PHP`**

```php title="PHP"
$apiClient->getConfig()->addDefaultHeader("X-DocuSign-Act-On-Behalf", $userId);
$envelopeApi = new EnvelopesApi($apiClient);

$fromDate = date("c", (time() - (10 * 24 * 60 * 60)));
$options = new ListStatusChangesOptions();
$options->setFromDate($fromDate);

try {
    $statusChanges = $envelopeApi->listStatusChangesWithHttpInfo($accountId, $options);

    $remaining = $statusChanges[2]['X-RateLimit-Remaining'] ?? null;
    $reset = $statusChanges[2]['X-RateLimit-Reset'] ?? null;

    if ($remaining !== null && $reset !== null) {
        $resetInstant = (new DateTime())->setTimestamp((int)$reset);
        error_log("API calls remaining: $remaining");
        error_log("Next Reset: " . $resetInstant->format(\DateTime::ATOM));
    }
} catch (ApiException $e) {
    error_log($e->getMessage());
}

return $statusChanges[0];
```

**`PowerShell`**

```text title="PowerShell"
try {
    # Make the API call to check the envelope
    # Get date in the ISO 8601 format
    $fromDate = ((Get-Date).AddDays(-10d)).ToString("yyyy-MM-ddThh:mm:ssK")

    $response = New-TemporaryFile

    Invoke-RestMethod `
        -Uri "${apiUri}/v2.1/accounts/${accountId}/envelopes" `
        -Method 'GET' `
        -Headers @{
        'X-DocuSign-Act-On-Behalf' = $userId;
        'Authorization' = "Bearer $accessToken";
        'Content-Type'  = "application/json";
    } `
        -Body @{ "from_date" = ${fromDate} } `
        -OutFile $response

    if ([string]::IsNullOrEmpty($response))
    {
        Write-Output ""
        Write-Output "Response body is empty because there are no envelopes in the account. Please run example 2 and re-run this example."
    } else {
        Write-Output ""
        Write-Output "Response:"
        Write-Output ""

        Get-Content $response
    }
```

**`Python`**

```python title="Python"
@classmethod
def get_envelopes(cls, args):
    api_client = create_api_client(base_path=args["base_path"], access_token=args["access_token"])
    api_client.set_default_header("X-DocuSign-Act-On-Behalf", args["user_id"])
    envelopes_api = EnvelopesApi(api_client)

    from_date = (dt.utcnow() - timedelta(days=10)).isoformat()
    (envelopes, status, headers) = envelopes_api.list_status_changes_with_http_info(account_id=args["account_id"], from_date=from_date)

    remaining = headers.get("X-RateLimit-Remaining")
    reset = headers.get("X-RateLimit-Reset")

    if remaining is not None and reset is not None:
        reset_date = dt.fromtimestamp(int(reset), tz=timezone.utc)
        print(f"API calls remaining: {remaining}")
        print(f"Next Reset: {reset_date}")

    return envelopes
```

**`Ruby`**

```ruby title="Ruby"
configuration = DocuSign_eSign::Configuration.new
configuration.host = args[:base_path]
api_client = DocuSign_eSign::ApiClient.new configuration
api_client.default_headers['Authorization'] = "Bearer #{args[:access_token]}"
api_client.set_default_header('X-DocuSign-Act-On-Behalf', args[:user_id])
envelopes_api = DocuSign_eSign::EnvelopesApi.new api_client

options = DocuSign_eSign::ListStatusChangesOptions.new
options.from_date = (Date.today - 10).strftime('%Y/%m/%d')
results, _status, headers = envelopes_api.list_status_changes_with_http_info args[:account_id], options

remaining = headers['X-RateLimit-Remaining']
reset = headers['X-RateLimit-Reset']

if remaining && reset
  reset_date = Time.at(reset.to_i).utc
  puts "API calls remaining: #{remaining}"
  puts "Next Reset: #{reset_date}"
end
```

## Expected response

If you run this code example from our Quickstart or launcher projects, you should see a JSON response  of the envelopes in the principal’s account.

**`Sample response`**

```json title="Sample response"
{
  "resultSetSize": "1",
  "startPosition": "0",
  "endPosition": "1",
  "totalSetSize": "1",
  "nextUri": "",
  "previousUri": "",
  "envelopes": [
      {
      "status": "sent",
      "documentsUri": "/envelopes/e63fd3e2-xxxx-xxxx-xxxx-5a73e59c7f9d/documents",
      "recipientsUri": "/envelopes/e63fd3e2-xxxx-xxxx-xxxx-5a73e59c7f9d/recipients",
      "attachmentsUri": "/envelopes/e63fd3e2-xxxx-xxxx-xxxx-5a73e59c7f9d/attachments",
      "envelopeUri": "/envelopes/e63fd3e2-xxxx-xxxx-xxxx-5a73e59c7f9d",
      "emailSubject": "Please sign this document set",
      "envelopeId": "e63fd3e2-xxxx-xxxx-xxxx-5a73e59c7f9d",
      "signingLocation": "online",
      "customFieldsUri": "/envelopes/e63fd3e2-xxxx-xxxx-xxxx-5a73e59c7f9d/custom_fields",
      "notificationUri": "/envelopes/e63fd3e2-xxxx-xxxx-xxxx-5a73e59c7f9d/notification",
      "allowMarkup": "false",
      "createdDateTime": "2023-04-12T01:09:04.2170000Z",
      "lastModifiedDateTime": "2023-04-12T01:09:04.2330000Z",
      "sentDateTime": "2023-04-12T01:09:05.5600000Z",
      "statusChangedDateTime": "2023-04-12T01:09:05.5600000Z",
      "documentsCombinedUri": "/envelopes/e63fd3e2-xxxx-xxxx-xxxx-5a73e59c7f9d/documents/combined",
      "certificateUri": "/envelopes/e63fd3e2-xxxx-xxxx-xxxx-5a73e59c7f9d/documents/certificate",
      "templatesUri": "/envelopes/e63fd3e2-xxxx-xxxx-xxxx-5a73e59c7f9d/templates",
      "expireEnabled": "true",
      "expireAfter": "120",
      "sender": {
        "userName": "Susan Signer",
        "userId": "c316f86c-xxxx-xxxx-xxxx-6b39358381d2",
        "accountId": "b71dbd28-xxxx-xxxx-xxxx-8d99842a7982",
        "email": "test@example.com",
        "ipAddress": "12.xxx.xxx.35"
      },
      "purgeState": "unpurged",
      "envelopeIdStamping": "true",
      "autoNavigation": "true",
      "isSignatureProviderEnvelope": "false",
      "anySigner": null,
      "envelopeLocation": "not_specified"
    }
  ]
}
```

## Next steps

* Run this code example from our [Quickstart](/docs/esign-rest-api/quickstart) or launcher projects:    [Bash](https://github.com/docusign/code-examples-bash), [C#](https://github.com/docusign/code-examples-csharp), [Java](https://github.com/docusign/code-examples-java), [Node.js](https://github.com/docusign/code-examples-node), [PHP](https://github.com/docusign/code-examples-php), [PowerShell](https://github.com/docusign/code-examples-powershell), [Python](https://github.com/docusign/code-examples-python), or [Ruby](https://github.com/docusign/code-examples-ruby).
* Learn more about [How to update individual permission settings](/docs/esign-rest-api/how-to/permission-profile-updating).
* See how to [Go-Live](/docs/esign-rest-api/go-live) with a completed app and find the base path for API calls in the production environment.