---
title: "OAuthTokens"
description: "OAuthTokens"
url: "https://www.contentstack.com/docs/developers/sdks/content-management-sdk/java/reference/oauthtokens"
product: "Contentstack"
doc_type: "guide"
audience:
  - developers
  - admins
version: "current"
last_updated: "2026-11-18"
---

# OAuthTokens

## OAuthTokens

OAuthTokens holds the tokens that Contentstack returns after an Open Authorization (OAuth) sign-in. It also holds their expiry, the granted scopes, and the organization and user UIDs. Use this class to

*   read the organization UID or user UID after sign-in
*   check whether the access token has expired
*   save the tokens and restore them in a later run

The SDK creates the object from the token response. Get it from the future that the [exchangeCodeForToken](/docs/developers/sdks/content-management-sdk/java/reference/oauthhandler#oauthhandler-exchangecodefortoken) or [refreshAccessToken](/docs/developers/sdks/content-management-sdk/java/reference/oauthhandler#oauthhandler-refreshaccesstoken) method of OAuthHandler returns, from [getTokens](/docs/developers/sdks/content-management-sdk/java/reference/oauthhandler#oauthhandler-gettokens), or from the onTokensUpdated method of your TokenCallback. To restore saved tokens, create an empty object with new OAuthTokens(), fill it with the setters, and pass it to the [setTokens](/docs/developers/sdks/content-management-sdk/java/reference/oauthhandler#oauthhandler-settokens) method of OAuthHandler.

## getAccessToken

getAccessToken returns the access token that the SDK sends with every request of an Open Authorization (OAuth) client.

```
Returns: String. The access token, or null.
ValidationThere is no client-side validation.getAccessToken does not throw.BehaviorThe value comes from access_token in the token response.Returns null on an object that you create with new OAuthTokens() until you call setAccessToken.The SDK sends the value in the Authorization header as Bearer <token>.The value is a secret. Do not log it. toString hides it.ExampleBasic usage: check the access token after sign-inimport com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.OAuthTokens;

import java.util.Scanner;
import java.util.concurrent.ExecutionException;

public class ReadAccessToken {
    public static void main(String[] args) throws InterruptedException {
        Contentstack client = new Contentstack.Builder()
                .setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
                .build();
        System.out.println("Open this URL and sign in: " + client.getOAuthHandler().authorize());
        System.out.print("Paste the code from the redirect URI: ");
        String code = new Scanner(System.in).nextLine();

        try {
            OAuthTokens tokens = client.getOAuthHandler().exchangeCodeForToken(code).get();
            String accessToken = tokens.getAccessToken();
            System.out.println(accessToken != null ? "Signed in" : "No access token");
        } catch (ExecutionException e) {
            // The token request failed. The cause holds the reason.
            System.out.println("Sign-in failed: " + e.getCause().getMessage());
        }
    }
}
```

## getExpiresAt

getExpiresAt returns the time at which the access token expires.

```
Returns: Date. A copy of the expiry time, or null.
ValidationThere is no client-side validation.getExpiresAt does not throw.BehaviorFor tokens from the SDK, the value is the time the SDK read the token response plus expires_in seconds.Returns null when the tokens hold no expiry time. isExpired then returns true.The returned Date is a copy. Changing it does not change the tokens. Use setExpiresAt instead.ExampleBasic usage: print the expiry timeimport com.contentstack.cms.models.OAuthTokens;
import java.util.Date;

public class ReadExpiresAt {
    public static void main(String[] args) {
        OAuthTokens tokens = new OAuthTokens();
        tokens.setExpiresIn(3600L);
        Date expiresAt = tokens.getExpiresAt();
        System.out.println("Expires at " + expiresAt);
    }
}
```

## getExpiresIn

getExpiresIn returns the lifetime of the access token, in seconds, as the SDK last stored it.

```
Returns: Long. The token lifetime in seconds, or null.
ValidationThere is no client-side validation.getExpiresIn does not throw.BehaviorThe value comes from expires_in in the token response.The value does not count down. setExpiresAt recalculates it as the seconds left at the moment of that call. Use getTimeUntilExpiration for the time left now.Returns null when the response carried no expires_in and no setter set a value.ExampleBasic usage: read the lifetimeimport com.contentstack.cms.models.OAuthTokens;

public class ReadExpiresIn {
    public static void main(String[] args) {
        OAuthTokens tokens = new OAuthTokens();
        tokens.setExpiresIn(3600L);
        System.out.println(tokens.getExpiresIn()); // 3600, or 3599 when the clock ticks during the call
    }
}
```

## getIssuedAt

getIssuedAt returns the creation time of the object.

```
Returns: Date. A copy of the creation time.
ValidationThere is no client-side validation.getIssuedAt does not throw.BehaviorFor tokens from the SDK, the value is the time the SDK read the token response, not a time from the server.new OAuthTokens() sets the value to the current time.The returned Date is a copy. Changing it does not change the tokens.ExampleBasic usage: read the creation timeimport com.contentstack.cms.models.OAuthTokens;
import java.util.Date;

public class ReadIssuedAt {
    public static void main(String[] args) {
        OAuthTokens tokens = new OAuthTokens();
        Date issuedAt = tokens.getIssuedAt();
        System.out.println("Created at " + issuedAt);
    }
}
```

## getOrganizationUid

getOrganizationUid returns the UID of the organization that the user authorized the app for.

```
Returns: String. The organization UID, or null.
ValidationThere is no client-side validation.getOrganizationUid does not throw.BehaviorThe value comes from organization_uid in the token response.On an Open Authorization (OAuth) client, the no-argument organization method of Contentstack uses this value to scope the Organization it returns.ExampleBasic usage: open the authorized organizationimport com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.OAuthTokens;
import com.contentstack.cms.organization.Organization;

import java.util.Scanner;
import java.util.concurrent.ExecutionException;

public class ReadOrganizationUid {
    public static void main(String[] args) throws InterruptedException {
        Contentstack client = new Contentstack.Builder()
                .setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
                .build();
        System.out.println("Open this URL and sign in: " + client.getOAuthHandler().authorize());
        System.out.print("Paste the code from the redirect URI: ");
        String code = new Scanner(System.in).nextLine();

        try {
            OAuthTokens tokens = client.getOAuthHandler().exchangeCodeForToken(code).get();
            String organizationUid = tokens.getOrganizationUid();
            if (organizationUid != null) {
                Organization organization = client.organization(organizationUid);
                System.out.println("Organization: " + organizationUid);
            }
        } catch (ExecutionException e) {
            // The token request failed. The cause holds the reason.
            System.out.println("Sign-in failed: " + e.getCause().getMessage());
        }
    }
}
```

## getRefreshToken

getRefreshToken returns the refresh token that the SDK uses to get a new access token.

```
Returns: String. The refresh token, or null.
ValidationThere is no client-side validation.getRefreshToken does not throw.BehaviorThe value comes from refresh_token in the token response.When a refresh response carries no refresh token, the SDK keeps the earlier one.Without a refresh token, the SDK cannot refresh an expired access token, and the next request fails. Check with the hasRefreshToken method.The value is a secret. Store it securely if you save it between runs.ExampleBasic usage: save the refresh token for a later runimport com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.OAuthTokens;

import java.util.Scanner;
import java.util.concurrent.ExecutionException;

public class SaveRefreshToken {
    public static void main(String[] args) throws InterruptedException {
        Contentstack client = new Contentstack.Builder()
                .setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
                .build();
        System.out.println("Open this URL and sign in: " + client.getOAuthHandler().authorize());
        System.out.print("Paste the code from the redirect URI: ");
        String code = new Scanner(System.in).nextLine();

        try {
            OAuthTokens tokens = client.getOAuthHandler().exchangeCodeForToken(code).get();
            if (tokens.hasRefreshToken()) {
                String refreshToken = tokens.getRefreshToken();
                // Save refreshToken in your secret store
                System.out.println("Refresh token length: " + refreshToken.length());
            }
        } catch (ExecutionException e) {
            // The token request failed. The cause holds the reason.
            System.out.println("Sign-in failed: " + e.getCause().getMessage());
        }
    }
}
```

## getScope

getScope returns the scopes that the user granted, as one string separated by spaces.

```
Returns: String. The space-separated scopes, or null.
ValidationThere is no client-side validation.getScope does not throw.BehaviorThe value comes from scope in the token response.Returns null when the response carried no scope.getScopesList returns the same scopes as a list.ExampleBasic usage: print the granted scopesimport com.contentstack.cms.models.OAuthTokens;

public class ReadScope {
    public static void main(String[] args) {
        OAuthTokens tokens = new OAuthTokens();
        tokens.setScope("user:read cm.stacks.management:read");
        String scope = tokens.getScope();
        if (scope != null && !scope.trim().isEmpty()) {
            System.out.println(scope);
        }
    }
}
```

## getScopesList

getScopesList returns the granted scopes as a list, one scope per element.

```
Returns: List<String>. The scopes as a list.
ValidationThere is no client-side validation.Known issue: In 1.16.0 on Java 8, getScopesList throws NoSuchMethodError when the tokens hold no scope, because the SDK calls a method that Java 9 added. Check that getScope returns a non-empty value first, or run on Java 9 or later.BehaviorgetScopesList splits the scope string at each single space. Two spaces in a row give an empty element.Returns an empty list when the tokens hold no scope.The returned list has a fixed size. Calling add or remove on it throws UnsupportedOperationException. Copy it into a new ArrayList to change it.ExampleBasic usage: list the scopesimport com.contentstack.cms.models.OAuthTokens;
import java.util.List;

public class ListScopes {
    public static void main(String[] args) {
        OAuthTokens tokens = new OAuthTokens();
        tokens.setScope("user:read cm.stacks.management:read");
        List<String> scopes = tokens.getScopesList();
        for (String scope : scopes) {
            System.out.println(scope);
        }
    }
}
```

## getStackApiKey

getStackApiKey returns the API key of a stack when the token response includes one.

```
Returns: String. The stack API key, or null.
ValidationThere is no client-side validation.getStackApiKey does not throw.BehaviorThe value comes from stack_api_key in the token response.Returns null when the response carried no stack_api_key.ExampleBasic usage: read the stack API keyimport com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.OAuthTokens;

import java.util.Scanner;
import java.util.concurrent.ExecutionException;

public class ReadStackApiKey {
    public static void main(String[] args) throws InterruptedException {
        Contentstack client = new Contentstack.Builder()
                .setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
                .build();
        System.out.println("Open this URL and sign in: " + client.getOAuthHandler().authorize());
        System.out.print("Paste the code from the redirect URI: ");
        String code = new Scanner(System.in).nextLine();

        try {
            OAuthTokens tokens = client.getOAuthHandler().exchangeCodeForToken(code).get();
            String apiKey = tokens.getStackApiKey();
            System.out.println(apiKey != null ? "Stack: " + apiKey : "No stack in the token response");
        } catch (ExecutionException e) {
            // The token request failed. The cause holds the reason.
            System.out.println("Sign-in failed: " + e.getCause().getMessage());
        }
    }
}
```

## getTimeUntilExpiration

getTimeUntilExpiration returns the number of milliseconds until the access token expires.

```
Returns: long. The milliseconds left before expiry.
ValidationThere is no client-side validation.getTimeUntilExpiration does not throw.BehaviorReturns 0 when the tokens hold no expiry time or the expiry time has passed.The value does not subtract the two-minute margin of isExpired. isExpired returns true while this method still returns up to 120000.ExampleBasic usage: print the minutes leftimport com.contentstack.cms.models.OAuthTokens;

public class PrintTimeLeft {
    public static void main(String[] args) {
        OAuthTokens tokens = new OAuthTokens();
        tokens.setExpiresIn(1800L);
        long minutesLeft = tokens.getTimeUntilExpiration() / 60000L;
        System.out.println(minutesLeft + " minutes left"); // 29 or 30
    }
}
```

## getTokenType

getTokenType returns the token type from the token response.

```
Returns: String. The token type, or null.
ValidationThere is no client-side validation.getTokenType does not throw.BehaviorThe value comes from token_type in the token response.isValid returns true only when this value is Bearer, in any letter case.The SDK sends the access token with the Bearer prefix whatever this value is.ExampleBasic usage: read the token typeimport com.contentstack.cms.models.OAuthTokens;

public class ReadTokenType {
    public static void main(String[] args) {
        OAuthTokens tokens = new OAuthTokens();
        System.out.println(tokens.getTokenType()); // null
        tokens.setTokenType("Bearer");
        System.out.println(tokens.getTokenType()); // Bearer
    }
}
```

## getUserUid

getUserUid returns the UID of the user who signed in.

```
Returns: String. The user UID, or null.
ValidationThere is no client-side validation.getUserUid does not throw.BehaviorThe value comes from user_uid in the token response.Returns null when the response carried no user_uid.ExampleBasic usage: read the user UIDimport com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.OAuthTokens;

import java.util.Scanner;
import java.util.concurrent.ExecutionException;

public class ReadUserUid {
    public static void main(String[] args) throws InterruptedException {
        Contentstack client = new Contentstack.Builder()
                .setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
                .build();
        System.out.println("Open this URL and sign in: " + client.getOAuthHandler().authorize());
        System.out.print("Paste the code from the redirect URI: ");
        String code = new Scanner(System.in).nextLine();

        try {
            OAuthTokens tokens = client.getOAuthHandler().exchangeCodeForToken(code).get();
            System.out.println("Signed in as user " + tokens.getUserUid());
        } catch (ExecutionException e) {
            // The token request failed. The cause holds the reason.
            System.out.println("Sign-in failed: " + e.getCause().getMessage());
        }
    }
}
```

## hasAccessToken

hasAccessToken reports whether the tokens hold an access token.

```
Returns: boolean. True when an access token is present.
ValidationThere is no client-side validation.hasAccessToken does not throw.BehaviorReturns false for null, an empty string, or a string of spaces.hasAccessToken does not check expiry. Use isExpired for that.ExampleBasic usage: check for an access tokenimport com.contentstack.cms.models.OAuthTokens;

public class CheckAccessToken {
    public static void main(String[] args) {
        OAuthTokens tokens = new OAuthTokens();
        System.out.println(tokens.hasAccessToken()); // false
        tokens.setAccessToken(" ");
        System.out.println(tokens.hasAccessToken()); // false, blank
    }
}
```

## hasRefreshToken

hasRefreshToken reports whether the tokens hold a refresh token.

```
Returns: boolean. True when a refresh token is present.
ValidationThere is no client-side validation.hasRefreshToken does not throw.BehaviorReturns false for null, an empty string, or a string of spaces.Without a refresh token, the SDK cannot refresh an expired access token, and it does not retry a 401 response with a new token.ExampleBasic usage: check before a long-running jobimport com.contentstack.cms.models.OAuthTokens;

public class CheckRefreshToken {
    public static void main(String[] args) {
        OAuthTokens tokens = new OAuthTokens();
        tokens.setRefreshToken(System.getenv("CONTENTSTACK_REFRESH_TOKEN"));
        if (!tokens.hasRefreshToken()) {
            System.out.println("Sign in again before the access token expires");
        }
    }
}
```

## hasScope

hasScope reports whether the granted scopes include the scope you name.

```
Returns: boolean. True when the tokens include the scope.
ValidationThere is no client-side validation.Known issue: In 1.16.0 on Java 8, hasScope throws NoSuchMethodError when the tokens hold no scope, because the SDK calls a method that Java 9 added. Check that getScope returns a non-empty value first, or run on Java 9 or later.BehaviorThe match is exact and case-sensitive. hasScope("user:read") does not match User:Read.Returns false when the tokens hold no scope, on Java 9 or later.ExampleBasic usage: check a scope before a requestimport com.contentstack.cms.models.OAuthTokens;

public class CheckScope {
    public static void main(String[] args) {
        OAuthTokens tokens = new OAuthTokens();
        tokens.setScope("user:read cm.stacks.management:read");
        if (tokens.hasScope("cm.stacks.management:read")) {
            System.out.println("The app can read stacks");
        }
    }
}
```

Scope to look for, matched exactly.

## isExpired

isExpired reports whether the access token has expired or expires within the next two minutes.

```
Returns: boolean. True when the access token has expired or expires soon.
ValidationThere is no client-side validation.isExpired does not throw.BehaviorisExpired returns true in each of the three cases below:The tokens hold no expiry time.The tokens hold no access token, or a blank one.The expiry time is two minutes (120 seconds) away or less.Before each request of an Open Authorization (OAuth) client, the SDK refreshes the tokens when this method returns true.ExampleBasic usage: check expiry with the two-minute marginimport com.contentstack.cms.models.OAuthTokens;

public class CheckExpiry {
    public static void main(String[] args) {
        OAuthTokens tokens = new OAuthTokens();
        tokens.setAccessToken(System.getenv("CONTENTSTACK_ACCESS_TOKEN"));
        tokens.setExpiresIn(600L);
        System.out.println(tokens.isExpired()); // false, 10 minutes left
        tokens.setExpiresIn(60L);
        System.out.println(tokens.isExpired()); // true, inside the two-minute margin
    }
}
```

## isValid

isValid reports whether the tokens hold an access token that has not expired and has the type Bearer.

```
Returns: boolean. True when the tokens are usable Bearer tokens.
ValidationThere is no client-side validation.isValid does not throw.BehaviorReturns true only when all three checks below pass:hasAccessToken returns true.isExpired returns false.getTokenType returns Bearer, in any letter case.Tokens that you restore without setTokenType("Bearer") are never valid by this check.The SDK does not call isValid before a request. It checks only isExpired.ExampleBasic usage: check restored tokensimport com.contentstack.cms.models.OAuthTokens;

public class CheckValidTokens {
    public static void main(String[] args) {
        OAuthTokens tokens = new OAuthTokens();
        tokens.setAccessToken(System.getenv("CONTENTSTACK_ACCESS_TOKEN"));
        tokens.setExpiresIn(3600L);
        System.out.println(tokens.isValid()); // false, no token type
        tokens.setTokenType("Bearer");
        System.out.println(tokens.isValid()); // true while an access token is set
    }
}
```

## setExpiresAt

setExpiresAt sets the time at which the access token expires.

```
Returns: void. This method returns nothing.
ValidationThere is no client-side validation. A time in the past makes isExpired return true.null clears the expiry time, so isExpired returns true.BehaviorsetExpiresAt stores a copy of the Date. Changing your Date later does not change the tokens.For a value that is not null, setExpiresAt also sets the lifetime to the seconds left from now. The lifetime is negative for a time in the past.Use this method to restore saved tokens with their original expiry time.ExampleBasic usage: restore a saved expiry timeimport com.contentstack.cms.models.OAuthTokens;
import java.util.Date;

public class RestoreExpiryTime {
    public static void main(String[] args) {
        long savedExpiry = System.currentTimeMillis() + 30L * 60L * 1000L; // read from your store
        OAuthTokens tokens = new OAuthTokens();
        tokens.setAccessToken(System.getenv("CONTENTSTACK_ACCESS_TOKEN"));
        tokens.setExpiresAt(new Date(savedExpiry));
        System.out.println(tokens.getExpiresIn()); // about 1800 seconds
    }
}
```

Time at which the access token expires.

## setExpiresIn

setExpiresIn sets the lifetime of the access token in seconds and calculates the expiry time from now.

```
Returns: void. This method returns nothing.
ValidationThere is no client-side validation. A negative value sets an expiry time in the past, so isExpired returns true.null clears the lifetime and leaves the expiry time unchanged.BehaviorFor a value that is not null, the expiry time becomes the current time plus expiresIn seconds.setExpiresIn then recalculates the stored lifetime from that expiry time, so getExpiresIn can return one second less than the value you passed.Changing the tokens that the client holds changes when the SDK refreshes them.ExampleBasic usage: restore tokens with a one-hour lifetimeimport com.contentstack.cms.models.OAuthTokens;

public class RestoreTokenLifetime {
    public static void main(String[] args) {
        OAuthTokens tokens = new OAuthTokens();
        tokens.setAccessToken(System.getenv("CONTENTSTACK_ACCESS_TOKEN"));
        tokens.setExpiresIn(3600L);
        System.out.println(tokens.isExpired()); // false while an access token is set
    }
}
```

Lifetime of the access token in seconds from now.

## setScopesList

setScopesList joins a list of scopes with spaces and stores the result as the scope string.

```
Returns: void. This method returns nothing.
ValidationThere is no client-side validation.null or an empty list clears the scopes, so getScope returns null.BehaviorThe list ["user:read", "cm.stacks.management:read"] becomes the string user:read cm.stacks.management:read.The SDK does not send the scopes of the tokens with requests. The value changes only what getScope, getScopesList and hasScope return.ExampleBasic usage: restore saved scopesimport com.contentstack.cms.models.OAuthTokens;
import java.util.Arrays;

public class RestoreScopes {
    public static void main(String[] args) {
        OAuthTokens tokens = new OAuthTokens();
        tokens.setScopesList(Arrays.asList("user:read", "cm.stacks.management:read"));
        System.out.println(tokens.getScope()); // user:read cm.stacks.management:read
    }
}
```

Scopes to store. null or an empty list clears them.

## toString

toString returns a one-line summary of the tokens that hides the access token and the refresh token.

```
Returns: String. A summary of the tokens with secrets hidden.
ValidationThere is no client-side validation.toString does not throw.BehaviorThe summary shows [REDACTED] in place of each token the object holds, and null for each token it does not hold.The summary shows the other values as stored: token type, lifetime, scope, organization UID, user UID, stack API key, creation time and expiry time.ExampleBasic usage: log the tokens safelyimport com.contentstack.cms.models.OAuthTokens;

public class LogTokens {
    public static void main(String[] args) {
        OAuthTokens tokens = new OAuthTokens();
        tokens.setAccessToken(System.getenv("CONTENTSTACK_ACCESS_TOKEN"));
        tokens.setTokenType("Bearer");
        System.out.println(tokens); // OAuthTokens{accessToken='[REDACTED]', refreshToken='null', tokenType='Bearer', ...}
    }
}
```

getAccessToken, setAccessToken. Token the SDK sends in the Authorization header.

getRefreshToken, setRefreshToken. Token that gets a new access token.

getTokenType, setTokenType. Token type from the response.

getExpiresIn, setExpiresIn. Lifetime of the access token in seconds.

getScope, setScope, getScopesList, setScopesList. Granted scopes as one string with spaces between them.

getOrganizationUid, setOrganizationUid. UID of the authorized organization.

getUserUid, setUserUid. UID of the signed-in user.

getStackApiKey, setStackApiKey. API key of a stack, when the response includes one.

getIssuedAt, setIssuedAt. Creation time of the object.

getExpiresAt, setExpiresAt. Time the access token expires.

## OAuthTokens | Java Management SDK | Contentstack

The OAuthTokens class in the Java Management SDK holds the access token, refresh token, expiry and account details from an OAuth sign-in.