> 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 Audit Users

This topic demonstrates how to audit the users in your account by retrieving the profiles of users that were modified after a specified date.

> **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                                                                                                                                                                                                                                                                                                        |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| \{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.                           |
| Admin access       | The caller must be an eSignature account administrator.                                                                                                                                                                                                                                                            |
| \{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>/management Where \<domain> is api-d.docusign.net for the developer environment and api.docusign.net for production.             |
| \{ORGANIZATION_ID} | A [GUID](http://guid.one/) value that identifies the the organization that contains the account to which the user will be added. Copy the value from the **Organization ID** field in the **Organization** section of the [Account Profile](https://admindemo.docusign.com/authenticate?goTo=accountProfile) 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.

Docusign Admin OAuth access tokens are the same ones used for our [eSignature REST API](/docs/esign-rest-api/esign101/auth), although you must request one or more Docusign Admin scopes to call the Docusign Admin API. The endpoint calls made in this how-to require that you request the Docusign Admin-specific `user_write` scope when obtaining your access token.

> **Note**
>
> See [Docusign Admin Authentication](/docs/admin-api/admin101/auth) for details and the full list of Docusign Admin scopes.

![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 apiClient = new DocuSignClient(basePath);
apiClient.Configuration.DefaultHeader.Add("Authorization", "Bearer " + accessToken);
```

**`Java`**

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

**`Node.js`**

```javascript title="Node.js"
let dsApiClient = new docusignAdmin.ApiClient();
dsApiClient.setBasePath(dsConfig.adminAPIUrl);
dsApiClient.addDefaultHeader('Authorization', 'Bearer ' + args.accessToken);
```

**`PHP`**

```php title="PHP"
$config = new Configuration();
$config->setAccessToken($accessToken);
$config->setHost('https://api-d.docusign.net/management');
$config->addDefaultHeader('Authorization', 'Bearer ' . $accessToken);
$this->apiClient = new ApiClient($config);
```

**`PowerShell`**

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

**`Python`**

```python title="Python"
api_client = ApiClient(host=DS_CONFIG["admin_api_client_host"])
api_client.set_default_header(
    header_name="Authorization",
    header_value=f"Bearer {access_token}"
)
```

**`Ruby`**

```ruby title="Ruby"
configuration = DocuSign_Admin::Configuration.new
configuration.host = Rails.configuration.admin_host

api_client = DocuSign_Admin::ApiClient.new(configuration)
api_client.set_default_header('Authorization', "Bearer #{args[:access_token]}")
```

## Step 3. Get a list of modified users

Now that you have constructed your API headers, make a GET request to the Admin API to retrieve the recently modified users in your account. Here’s how you make the call, but make sure to substitute your API account ID for \{ACCOUNT_ID} and your organization ID for \{ORGANIZATION_ID}.

**`Bash`**

```bash title="Bash"
# Calculate date parameter to get users modified in the last 10 days
if date -v -10d &>/dev/null; then
    # Mac
    # modified_since=`date -v -10d '+%Y-%m-%dT%H:%M:%S%z'`
    modified_since=$(date -v -10d '+%Y-%m-%d')
else
    # Not a Mac
    # modified_since=`date --date='-10 days' '+%Y-%m-%dT%H:%M:%S%z'`
    modified_since=$(date --date='-10 days' '+%Y-%m-%d')
fi

response=$(mktemp /tmp/response-admin.XXXXXX)

# Call the Admin API
Status=$(
    curl -w '%{http_code}' --request GET "${base_path}/v2/organizations/${ORGANIZATION_ID}/users?account_id=${API_ACCOUNT_ID}&last_modified_since${modified_since}" \
    "${Headers[@]}" \
    --output $response
)
```

**`C#`**

```csharp title="C#"
UsersApi usersApi = new UsersApi(apiClient);
int tenDaysAgo = -10;
var getUsersOptions = new UsersApi.GetUsersOptions
{
    accountId = accountId,
    lastModifiedSince = DateTime.Today.AddDays(tenDaysAgo).ToString("yyyy-MM-dd"),
};

var recentlyModifiedUsers = usersApi.GetUsersWithHttpInfo(orgId, getUsersOptions);
recentlyModifiedUsers.Headers.TryGetValue("X-RateLimit-Remaining", out string remaining);
recentlyModifiedUsers.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"
UsersApi.GetUsersOptions options = usersApi.new GetUsersOptions();
options.setAccountId(accountId);
TimeZone tz = TimeZone.getTimeZone(timeZoneId);
SimpleDateFormat df = new SimpleDateFormat(simpleDateFormat);
// Quoted "Z" to indicate UTC, no timezone offset
df.setTimeZone(tz);
Integer tenDaysBeforeToday = 1000 * 60 * 60 * 24 * 10;
String nowAsISO = df.format(new Date(System.currentTimeMillis() - tenDaysBeforeToday));
options.setLastModifiedSince(nowAsISO);
ApiResponse<OrganizationUsersResponse> modifiedUsers = usersApi.getUsersWithHttpInfo(organizationId, options);

Map<String, List<String>> headers = modifiedUsers.getHeaders();
List<String> remaining = headers.get("X-RateLimit-Remaining");
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);
}
```

**`Node.js`**

```javascript title="Node.js"
let options = {
  accountId: args.accountId,
  lastModifiedSince: moment().subtract(10, 'days').format()
};

const usersApi = new docusignAdmin.UsersApi(dsApiClient);
const allUsers = (await usersApi.getUsers(args.organizationId, 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()}`);
    }
}));
var modifiedUsers = allUsers.data.users;
```

**`PHP`**

```php title="PHP"
$options = new GetUsersOptions();
$options->setAccountId($arguments["account_id"]);
$from_date = date("c", (time() - (10 * 24 * 60 * 60)));
$options->setLastModifiedSince($from_date);

try {
    $modifiedUsers = $admin_api->getUsersWithHttpInfo($organizationId, $options);
```

**`PowerShell`**

```text title="PowerShell"
$modifiedSince = (Get-Date (Get-Date).AddDays(-10) -Format "yyyy-MM-dd")

try {
  # Display the JSON response
  Write-Output "Response:"
  $uri = "${base_path}/management/v2/organizations/${organizationId}/users?account_id=${APIAccountId}&last_modified_since=${modifiedSince}"
  $response = Invoke-WebRequest -uri $uri -UseBasicParsing -headers $headers -method GET
  $response.Content | ConvertFrom-Json | ConvertTo-Json -Depth 4
  $modifiedUsers = $($response.Content | ConvertFrom-Json).users
}
catch {
  Write-Output "Error:"
  # On failure, display a notification, X-DocuSign-TraceToken, error message, and the command that triggered the error
  foreach ($header in $_.Exception.Response.Headers) {
    if ($header -eq "X-DocuSign-TraceToken") { Write-Output "TraceToken : " $_.Exception.Response.Headers[$int] }
    $int++
  }
  Write-Output "Error : "$_.ErrorDetails.Message
  Write-Output "Command : "$_.InvocationInfo.Line
  exit 1
}
```

**`Python`**

```python title="Python"
today = dt.now()
ten_days_ago = today - (timedelta(days = 10))
last_modified_since = ten_days_ago.strftime('%Y-%m-%d')

users_api = UsersApi(api_client=api_client)
(users, status, headers) = users_api.get_users_with_http_info(
    organization_id=org_id,
    account_id=account_id,
    last_modified_since=last_modified_since)

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"
options = DocuSign_Admin::GetUsersOptions.new
options.account_id = args[:account_id]
options.last_modified_since = (Date.today - 10).strftime('%Y/%m/%d')

users_api = DocuSign_Admin::UsersApi.new(api_client)
modified_users, _status, headers = users_api.get_users_with_http_info(args[:organization_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
```

## Step 4. Get the email addresses of the modified users

To get the profile of each modified user you will need to extract the email address of each user from the list of users returned in Step 3. The accompanying code demonstrates how to build a list of email addresses to be passed as parameters in your calls to [eSignUserManagement:getUserProfiles](/docs/admin-api/reference/usermanagement/esignusermanagement/getuserprofiles).

**`Bash`**

```bash title="Bash"
modified_users=$(cat $response)
user_emails=`echo $modified_users | grep -o -P '(?<=email\":\").*?(?=\")'`
array_emails=($user_emails)
```

**`C#`**

```csharp title="C#"
foreach (var user in recentlyModifiedUsers.Data.Users)
{
    var getUserProfilesOptions = new UsersApi.GetUserProfilesOptions { email = user.Email };
```

**`Java`**

```java title="Java"
UsersApi.GetUserProfilesOptions profilesOptions = usersApi.new GetUserProfilesOptions();
profilesOptions.setEmail(user.getEmail());
```

**`Node.js`**

```javascript title="Node.js"
opts.email = user.email;
```

**`PHP`**

```php title="PHP"
foreach ($modifiedUsers[0]["users"] as $user) {
    $profileOptions = new GetUserProfilesOptions();
    $profileOptions->setEmail($user["email"]);
```

**`PowerShell`**

```text title="PowerShell"
$userEmails = $modifiedUsers.email
```

**`Python`**

```python title="Python"
modified_users = users.users
emails = []
for user in modified_users:
    dict_user = user.to_dict()
    emails.append(dict_user["email"])
```

**`Ruby`**

```ruby title="Ruby"
userProfilesOptions = DocuSign_Admin::GetUserProfilesOptions.new
userProfilesOptions.email = user['email']
```

## Step 5. Call the Docusign Admin API

Using your list of user email addresses from Step 4, call the Admin API to get the user profile for the user associated with each email address. Here’s how you make the call, but make sure to substitute your organization ID for \{ORGANIZATION_ID}.

> **Note**
>
> View the source code for this how-to on GitHub: [Bash](https://github.com/docusign/code-examples-bash/blob/master/examples/Admin/eg005AuditUsers.sh), [C#](https://github.com/docusign/code-examples-csharp/blob/master/launcher-csharp/Admin/Examples/AuditUsers.cs), [Java](https://github.com/docusign/code-examples-java/blob/master/src/main/java/com/docusign/controller/admin/services/AuditUsersService.java), [Node.js](https://github.com/docusign/code-examples-node/blob/master/lib/admin/examples/auditUsers.js), [PHP](https://github.com/docusign/code-examples-php/blob/master/src/Services/Examples/Admin/AuditUsersService.php), [PowerShell](https://github.com/docusign/code-examples-powershell/blob/master/examples/Admin/eg005AuditUsers.ps1), [Python](https://github.com/docusign/code-examples-python/blob/master/app/admin/examples/eg005_audit_users.py), or [Ruby](https://github.com/docusign/code-examples-ruby/blob/master/app/services/admin_api/eg005_audit_users_service.rb)

**`Bash`**

```bash title="Bash"
profiles=$(mktemp /tmp/profiles-oa.XXXXXX)

echo ''
echo 'User profiles:'

for email in ${array_emails[@]}
do

    Status=$(
        curl -w '%{http_code}' -i --request GET "${base_path}/v2/organizations/${ORGANIZATION_ID}/users/profile?email=${email}" \
        "${Headers[@]}" \
        --output ${profiles}
    )

    echo ''
    cat $profiles
    echo ''

done
```

**`C#`**

```csharp title="C#"
var usersData = new List<UserDrilldownResponse>();
    var users = usersApi.GetUserProfilesWithHttpInfo(orgId, getUserProfilesOptions);
    users.Headers.TryGetValue("X-RateLimit-Remaining", out remaining);
    users.Headers.TryGetValue("X-RateLimit-Reset", out 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);
    }

    usersData.AddRange(users.Data.Users);
```

**`Java`**

```java title="Java"
for (OrganizationUserResponse user : modifiedUsers.getData().getUsers()) {
    ApiResponse<UsersDrilldownResponse> res = usersApi.getUserProfilesWithHttpInfo(organizationId,
            profilesOptions);

    headers = res.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);
    }

    auditedUsers.add(res.getData().getUsers().get(0));
}
```

**`Node.js`**

```javascript title="Node.js"
let results = [];
let opts = {};

for (const user of modifiedUsers) {
  const result = await usersApi.getUserProfiles(args.organizationId, opts);
  results.push(result.users);
}
```

**`PHP`**

```php title="PHP"
$usersInformation = [];
$userDrilldownResponse = new UsersDrilldownResponse();
        $res = $admin_api->getUserProfilesWithHttpInfo($organizationId, $profileOptions);
        $remaining = $res[2]['X-RateLimit-Remaining'] ?? null;
        $reset = $res[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));
        }
        $userDrilldownResponse->setUsers($res[0]->getUsers());
        $decoded = json_decode((string)$userDrilldownResponse, true);
        array_push($usersInformation, $decoded["users"]);
```

**`PowerShell`**

```text title="PowerShell"
foreach ($emailAddress in $userEmails){
  try {
    # Display the JSON response
    Write-Output "Response:"
    $uri = "${base_path}/management/v2/organizations/${organizationId}/users/profile?email=${emailAddress}"
    $response = Invoke-WebRequest -uri $uri -UseBasicParsing -headers $headers -method GET
    $response.Content | ConvertFrom-Json | ConvertTo-Json -Depth 4
  }
  catch {
    Write-Output "Error:"
    # On failure, display a notification, X-DocuSign-TraceToken, error message, and the command that triggered the error
    foreach ($header in $_.Exception.Response.Headers) {
      if ($header -eq "X-DocuSign-TraceToken") { Write-Output "TraceToken : " $_.Exception.Response.Headers[$int] }
      $int++
    }
    Write-Output "Error : "$_.ErrorDetails.Message
    Write-Output "Command : "$_.InvocationInfo.Line
    exit 1
  }
}
```

**`Python`**

```python title="Python"
profile_list = []
for email in emails:
    (profile, status, headers) = users_api.get_user_profiles_with_http_info(organization_id=org_id, email=email)

    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}")
    profile_list.append(profile.to_dict())

results = {"Modified users": profile_list}
```

**`Ruby`**

```ruby title="Ruby"
results = []
modified_users.as_json['users'].each do |user|
  result, _status, headers = users_api.get_user_profiles_with_http_info(args[:organization_id], userProfilesOptions)

  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

  results.push(result)
end
```

## Expected response

If your API call is successful, you should see a JSON response similar to this for each user.

**`Sample response`**

```json title="Sample response"
{
  "users": [
    {
      "id": "f5963dc2-xxxx-xxxx-xxxx-76d362ecaa40",
      "site_id": 1,
      "site_name": "Demo",
      "user_name": "User Name",
      "first_name": "User",
      "last_name": "Name",
      "user_status": "active",
      "default_account_id": "f7802c14-xxxx-xxxx-xxxx-65244a0dd179",
      "default_account_name": "DocuSign",
      "language_culture": "en",
      "is_organization_admin": true,
      "created_on": "2020-09-21T18:21:51.623",
      "memberships": [
        {
          "email": "1007a@example.com",
          "account_id": "f7802c14-xxxx-xxxx-xxxx-65244a0dd179",
          "external_account_id": "11xxxx42",
          "account_name": "DocuSign",
          "is_external_account": false,
          "status": "active",
          "permission_profile": {
            "id": 10xxxx51,
            "name": "Account Administrator"
          },
          "created_on": "2020-09-21T18:21:51.623",
          "groups": [
            {
              "id": 76xxx01,
              "name": "Administrators",
              "type": 1
            },
            {
              "id": 76xxx02,
              "name": "Everyone",
              "type": 2
            }
          ],
          "is_admin": true
        }
      ],
      "identities": [],
      "device_verification_enabled": true
    }
  ]
}
```

## 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).
* See [How to create a new active eSignature user](/docs/admin-api/how-to/create-active-user).
* Learn more about the new  [Admin API v2.1](/docs/admin-api/admin101/versioning).
* See how to [Go-Live](/docs/admin-api/go-live) with a completed app and find the base path for API calls in the production environment.