---
updatedAt: 2025-12-15T10:06:57.000Z
agentTools:
  projectIndex: https://developer.onetrust.com/onetrust/llms.txt
---

# Generate OAuth Access Token

```python Python
import requests
from datetime import datetime, timedelta

client_id = 'your_client_id'
client_secret = 'your_client_secret'
token_url = "https://app.onetrust.com/api/access/v1/oauth/token"

class OAuthClient:
    def __init__(self, client_id, client_secret, token_url):
        self.client_id = client_id
        self.client_secret = client_secret
        self.token_url = token_url
        self.access_token = None
        self.token_expiry = None

    def get_access_token(self):
        if self.access_token is None or self.is_token_expired():
            self.request_new_token()
        return self.access_token

    def is_token_expired(self):
        if self.token_expiry is None:
            return True
        return datetime.now() >= self.token_expiry

    def request_new_token(self):
        payload = {
            'grant_type': 'client_credentials',
            'client_id': self.client_id,
            'client_secret': self.client_secret
        }
        headers = {
            'Accept': 'application/json'
        }
        response = requests.post(self.token_url, headers=headers, data=payload)
        
        if response.status_code == 200:
            token_data = response.json()
            self.access_token = token_data['access_token']
            expires_in = token_data.get('expires_in', 3600)  # default to 1 hour if not provided
            self.token_expiry = datetime.now() + timedelta(seconds=expires_in)
        else:
            response.raise_for_status()  # Raise an error if the token request failed

oauth_client = OAuthClient(client_id, client_secret, token_url)
access_token = oauth_client.get_access_token()
print(access_token)

```

```java Java
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.Scanner;

import org.json.JSONObject;

public class OAuthClient {
    private String clientId;
    private String clientSecret;
    private String tokenUrl;
    private String accessToken;
    private long tokenExpiry;

    public OAuthClient(String clientId, String clientSecret, String tokenUrl) {
        this.clientId = clientId;
        this.clientSecret = clientSecret;
        this.tokenUrl = tokenUrl;
        this.accessToken = null;
        this.tokenExpiry = 0;
    }

    public String getAccessToken() throws IOException {
        if (accessToken == null || isTokenExpired()) {
            requestNewToken();
        }
        return accessToken;
    }

    private boolean isTokenExpired() {
        return System.currentTimeMillis() >= tokenExpiry;
    }

    private void requestNewToken() throws IOException {
        URL url = new URL(tokenUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "application/json");
        connection.setDoOutput(true);

        String auth = clientId + ":" + clientSecret;
        String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());
        String authHeaderValue = "Basic " + encodedAuth;
        connection.setRequestProperty("Authorization", authHeaderValue);
        String payload = "grant_type=client_credentials";

        connection.getOutputStream().write(payload.getBytes());

        if (connection.getResponseCode() == 200) {
            Scanner scanner = new Scanner(connection.getInputStream()).useDelimiter("\\A");
            String response = scanner.hasNext() ? scanner.next() : "";
            scanner.close();

            JSONObject json = new JSONObject(response);
            accessToken = json.getString("access_token");
            int expiresIn = json.getInt("expires_in");
            tokenExpiry = System.currentTimeMillis() + (expiresIn * 1000);
        } else {
            throw new IOException("Failed to obtain access token: " + connection.getResponseMessage());
        }
    }

    public static void main(String[] args) {
        try {
            OAuthClient oauthClient = new OAuthClient("your_client_id", "your_client_secret", "https://app.onetrust.com/api/access/v1/oauth/token");
            String accessToken = oauthClient.getAccessToken();
            System.out.println(accessToken);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
```

```powershell PowerShell
$clientId = 'your_client_id'
$clientSecret = 'your_client_secret'
$tokenUrl = "https://app.onetrust.com/api/access/v1/oauth/token"

class OAuthClient {
    [string]$ClientId
    [string]$ClientSecret
    [string]$TokenUrl
    [string]$AccessToken
    [datetime]$TokenExpiry

    OAuthClient([string]$clientId, [string]$clientSecret, [string]$tokenUrl) {
        $this.ClientId = $clientId
        $this.ClientSecret = $clientSecret
        $this.TokenUrl = $tokenUrl
        $this.AccessToken = $null
        $this.TokenExpiry = [datetime]::MinValue
    }

    [string]GetAccessToken() {
        if ($null -eq $this.AccessToken -or $this.IsTokenExpired()) {
            $this.RequestNewToken()
        }
        return $this.AccessToken
    }

    [bool]IsTokenExpired() {
        return [datetime]::UtcNow -ge $this.TokenExpiry
    }

    [void]RequestNewToken() {
        $payload = @{
            grant_type    = 'client_credentials'
            client_id     = $this.ClientId
            client_secret = $this.ClientSecret
        }
        $headers = @{
            Accept = 'application/json'
        }

        $response = Invoke-RestMethod -Uri $this.TokenUrl -Method Post -Headers $headers -Body $payload
        if ($response -ne $null) {
            $this.AccessToken = $response.access_token
            $expiresIn = $response.expires_in
            $this.TokenExpiry = [datetime]::UtcNow.AddSeconds($expiresIn)
        } else {
            throw "Failed to obtain access token"
        }
    }
}

$oauthClient = [OAuthClient]::new($clientId, $clientSecret, $tokenUrl)
$accessToken = $oauthClient.GetAccessToken()
Write-Output $accessToken

```

```node Node
const axios = require('axios');

const clientId = 'your_client_id';
const clientSecret = 'your_client_secret';
const tokenUrl = 'https://app.onetrust.com/api/access/v1/oauth/token';

class OAuthClient {
    constructor(clientId, clientSecret, tokenUrl) {
        this.clientId = clientId;
        this.clientSecret = clientSecret;
        this.tokenUrl = tokenUrl;
        this.accessToken = null;
        this.tokenExpiry = null;
    }

    async getAccessToken() {
        if (!this.accessToken || this.isTokenExpired()) {
            await this.requestNewToken();
        }
        return this.accessToken;
    }

    isTokenExpired() {
        return !this.tokenExpiry || new Date() >= this.tokenExpiry;
    }

    async requestNewToken() {
        try {
            const response = await axios.post(this.tokenUrl, new URLSearchParams({
                grant_type: 'client_credentials',
                client_id: this.clientId,
                client_secret: this.clientSecret
            }), {
                headers: {
                    'Accept': 'application/json'
                }
            });

            const data = response.data;
            this.accessToken = data.access_token;
            const expiresIn = data.expires_in || 3600; // default to 1 hour if not provided
            this.tokenExpiry = new Date(new Date().getTime() + expiresIn * 1000);
        } catch (error) {
            throw new Error(`Failed to obtain access token: ${error.message}`);
        }
    }
}

(async () => {
    const oauthClient = new OAuthClient(clientId, clientSecret, tokenUrl);
    const accessToken = await oauthClient.getAccessToken();
    console.log(accessToken);
})();

```

```json Response Example
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Imp3dCJ9eyJyb2xlIjoiQXBpIEtleSBVc2VyIiwidXN
lcl9uYW1lIjoiMzNkZjU5MGUzZmQ1NDRi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CIsInNjb3BlIjpbXSwidGVuYW50SWQiOjExODExLCJndW
lkIjoiNzgxMmQ4NjQtMTg5Mi00ZDQwLTgxZjctZDllMGIwNzM1ZDQwIiwiZXhwIjoxNzE3NjIzMjg2LCJleHBpc
mVzX2luIjozNjAwLCJqdGkiOiJNZ0FWRWFJT1RqTmRJQXJoQ1ZvOXlPUS1zdW8iLCJlbWFpbCI6IjMzZGY1OTBl
M2ZkNTQ0YmRhNTBmMzcyMjk4ODAyMWVkQGFwaS5vbmV0cnVzdC5jb20ifQE4KFUVWg43GHYfc3Qrcwp4USROY0d
NKmxUJHx3JwUqcDsiQzFLNCgBLVowdO+/vU40RV4nZDctSTsBIil6SwpM3JBGOiY7ZGtaTgo3OlhHd2FfKG0rF1
BKLTYpAnpeKzfLvFk1LS0TSkN9FzxRTn1lIUcEJH1qQDNDyZwHRXlLxqt2HzwtAlVAx7FjbEcCfV48SWlkRnIUL
e+/vQ== 
```

# Introduction



To get started with OneTrust APIs, you will first need to generate an access token. OAuth 2.0 Client Credentials can be created within Global Settings in the OneTrust application. When creating a Client Credential, you will need to select the necessary scope(s). OAuth scopes are required for each endpoint in order to send requests. Details about the OAuth scopes required for each endpoint are covered within the respective API Reference page for that endpoint. For more information, see [OAuth 2.0 Scopes](https://developer.onetrust.com/onetrust/docs/oauth-20-scopes).

# Update Client ID, Secret, & URL

<!-- python@4-6 -->
<!-- java@66 -->
<!-- powershell@1-4 -->
<!-- node@2-6 -->

When using OAuth 2.0 Client Credentials, you can generate the Client ID and Secret within the OneTrust application (**Global Settings > Access Management > Client Credentials > Client Credentials tab**). Validate the value for **Access Token Lifetime** under **Advanced Options**. This determines how long before the access token expires after being generated. Select the appropriate Scope(s) for your use case, then click **Create**. 

Copy and paste the Client ID and Secret values into `client_id` and `client_secret` respectively. Update the `token_url` if needed with your OneTrust application hostname.

# Class Initialization

<!-- python@8-14 -->
<!-- java@9-22 -->
<!-- powershell@4-19 -->
<!-- node@6-15 -->

The `OAuthClient` class is initialized with `client_id`, `client_secret`, and `token_url`. `access_token` and `token_expiry` are set to `None` initially.

# Get Access Token Method

<!-- python@16-19 -->
<!-- java@24-29 -->
<!-- powershell@19-26 -->
<!-- node@15-22 -->

This method checks if the current token is `None` or expired. If so, it requests a new token. It returns the current valid access token.

# Is Token Expired Method

<!-- python@21-24 -->
<!-- java@31-33 -->
<!-- powershell@26-30 -->
<!-- node@22-26 -->

This method checks if the token is expired by comparing the current time with the token expiry time.

# Request New Token Method

<!-- python@26-43 -->
<!-- java@35-62 -->
<!-- powershell@30-51 -->
<!-- node@26-48 -->

This method sends a POST request using the [Generate Access Token API](https://developer.onetrust.com/onetrust/reference/getoauthtoken) to obtain a new token using the provided client credentials.
If the request is successful, it extracts the `access_token` and calculates the token expiry time based on the `expires_in` value. If the request fails, it raises an error.


<details>
  <summary>Expand to see example response</summary>

```json
{
    "role": "Api Key User",
    "user_name": "33df590e3fd544bda50f3722988021eb@api.onetrust.com",
    "languageId": 1,
    "sessionId": "439682e7-a256-4f0e-a312-9c8ec5b219f5",
    "token_type": "Bearer",
    "tenantGuid": "33df590e-3fd5-44bd-a50f-3722988021ec",
    "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Imp3dCJ9eyJyb2xlIjoiQXBpIEtleSBVc2VyIiwidXNlcl9uYW1lIjoiMzNkZjU5MGUzZmQ1NDRiZGE1MGYzNzIyOTg4MDIxZWJAYXBpLm9uZXRydXN0LmNvbSIsImxhbmd1YWdlSWQiOjEsInNlc3Npb25JZCI6IjQzOTY4MmU3LWEyNTYtNGYwZS1hMzEyLTljOGVjNWIyMTlmNSIsInRlbmFudEd1aWQiOiIzM2RmNTkwZS0zZmQ1LTQ0YmQtYTUwZi0zNzIyOTg4MDIxZWIiLCJjbGllbnRfaWQiOiI4MjNhNTE2YTUxY2M0YjEyODY0MzE5MTQzYzI4ZTdlYyIsIm9yZ0dyb3VwSWQiOiJiN2QxN2ZjOC04ODlmLTQ3MmUtOGM3NC1mM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+/vU40RV4nZDctSTsBIil6SwpM3JBGOiY7ZGtaTgo3OlhHd2FfKG0rF1BKLTYpAnpeKzfLvFk1LS0TSkN9FzxRTn1lIUcEJH1qQDNDyZwHRXlLxqt2HzwtAlVAx7FjbEcCfV48SWlkRnIULe+/vQ==",
    "orgGroupId": "b7d17fc8-889f-472e-8c74-f1169821e7e7",
    "orgGroupGuid": "b7d17fc8-889f-472e-8c74-f1169821e7e7",
    "ot-scopes": "ADMIN,ASSESSMENT,ASSESSMENT_READ,ATTACHMENT,ATTACHMENT_READ,AUDIT_MANAGEMENT,BULK_EXPORT,CONSENT,CONSENT_READ,CONTROL,COOKIE,COOKIE_FREE,COOKIE_READ,DATA_CATALOG_READ,DATA_CATALOG_WRITE,DATA_DISCOVERY,DSAR_READ,DSAR_WRITE,ESG,ESG_READ,INCIDENT,INCIDENT_CREATE,INCIDENT_READ,INTEGRATION_JWKS,INTEGRATIONS,INVENTORY,INVENTORY_READ,INVENTORY_WRITE,ISSUE,ISSUE_READ,ITRM,OBJECT_MANAGER,OBJECT_MANAGER_READ,OBJECT_MANAGER_WRITE,ORGANIZATION,POLICY,RISK,SCIM,USER,VRM,VRM_READ",
    "tenantId": 11811,
    "guid": "7812d864-1892-4d40-81f7-d9e0b0735d40",
    "expires_in": 3600,
    "email": "33df590e3fd544bda50f3722988021eb@api.onetrust.com",
    "jti": "MgAVEaIOTjNdIArhCVo9yOQ-suo"
}
```
</details>

# Summary

<!-- python@45-47 -->
<!-- java@64-73 -->
<!-- powershell@51-55 -->
<!-- node@48-54 -->

This approach ensures that the token is always valid when needed and handles the process of refreshing it seamlessly.
You can leverage these methods in your application to ensure seamless access token renewal when the current token expires.