OAuthTokens

View as Markdown

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 or refreshAccessToken method of OAuthHandler returns, from 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 method of OAuthHandler.

NameTypeDescription
accessToken String

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

refreshToken String

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

tokenType String

getTokenType, setTokenType. Token type from the response.

expiresIn Long

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

scope String

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

organizationUid String

getOrganizationUid, setOrganizationUid. UID of the authorized organization.

userUid String

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

stackApiKey String

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

issuedAt Date

getIssuedAt, setIssuedAt. Creation time of the object.

expiresAt Date

getExpiresAt, setExpiresAt. Time the access token expires.

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.

Validation

  • There is no client-side validation.
  • getAccessToken does not throw.

Behavior

  • The 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.

Example

Basic usage: check the access token after sign-in

import 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.

Validation

  • There is no client-side validation.
  • getExpiresAt does not throw.

Behavior

  • For 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.

Example

Basic usage: print the expiry time

import 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.

Validation

  • There is no client-side validation.
  • getExpiresIn does not throw.

Behavior

  • The 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.

Example

Basic usage: read the lifetime

import 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.

Validation

  • There is no client-side validation.
  • getIssuedAt does not throw.

Behavior

  • For 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.

Example

Basic usage: read the creation time

import 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.

Validation

  • There is no client-side validation.
  • getOrganizationUid does not throw.

Behavior

  • The 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.

Example

Basic usage: open the authorized organization

import 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.

Validation

  • There is no client-side validation.
  • getRefreshToken does not throw.

Behavior

  • The 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.

Example

Basic usage: save the refresh token for a later run

import 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.

Validation

  • There is no client-side validation.
  • getScope does not throw.

Behavior

  • The value comes from scope in the token response.
  • Returns null when the response carried no scope.
  • getScopesList returns the same scopes as a list.

Example

Basic usage: print the granted scopes

import 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.

Validation

  • There 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.

Behavior

  • getScopesList 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.

Example

Basic usage: list the scopes

import 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.

Validation

  • There is no client-side validation.
  • getStackApiKey does not throw.

Behavior

  • The value comes from stack_api_key in the token response.
  • Returns null when the response carried no stack_api_key.

Example

Basic usage: read the stack API key

import 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.

Validation

  • There is no client-side validation.
  • getTimeUntilExpiration does not throw.

Behavior

  • Returns 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.

Example

Basic usage: print the minutes left

import 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.

Validation

  • There is no client-side validation.
  • getTokenType does not throw.

Behavior

  • The 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.

Example

Basic usage: read the token type

import 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.

Validation

  • There is no client-side validation.
  • getUserUid does not throw.

Behavior

  • The value comes from user_uid in the token response.
  • Returns null when the response carried no user_uid.

Example

Basic usage: read the user UID

import 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.

Validation

  • There is no client-side validation.
  • hasAccessToken does not throw.

Behavior

  • Returns false for null, an empty string, or a string of spaces.
  • hasAccessToken does not check expiry. Use isExpired for that.

Example

Basic usage: check for an access token

import 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.

Validation

  • There is no client-side validation.
  • hasRefreshToken does not throw.

Behavior

  • Returns 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.

Example

Basic usage: check before a long-running job

import 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.

NameTypeDescription
scopeToCheck (required)String

Scope to look for, matched exactly.

Default: Not applicable

Returns: boolean. True when the tokens include the scope.

Validation

  • There 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.

Behavior

  • The 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.

Example

Basic usage: check a scope before a request

import 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");
        }
    }
}

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.

Validation

  • There is no client-side validation.
  • isExpired does not throw.

Behavior

  • isExpired 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.

Example

Basic usage: check expiry with the two-minute margin

import 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.

Validation

  • There is no client-side validation.
  • isValid does not throw.

Behavior

  • Returns true only when all three checks below pass:
  • 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.

Example

Basic usage: check restored tokens

import 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.

NameTypeDescription
expiresAt (required)Date

Time at which the access token expires.

Default: Not applicable

Returns: void. This method returns nothing.

Validation

  • There is no client-side validation. A time in the past makes isExpired return true.
  • null clears the expiry time, so isExpired returns true.

Behavior

  • setExpiresAt 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.

Example

Basic usage: restore a saved expiry time

import 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
    }
}

setExpiresIn

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

NameTypeDescription
expiresIn (required)Long

Lifetime of the access token in seconds from now.

Default: Not applicable

Returns: void. This method returns nothing.

Validation

  • There 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.

Behavior

  • For 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.

Example

Basic usage: restore tokens with a one-hour lifetime

import 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
    }
}

setScopesList

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

NameTypeDescription
scopes (required)List<String>

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

Default: Not applicable

Returns: void. This method returns nothing.

Validation

  • There is no client-side validation.
  • null or an empty list clears the scopes, so getScope returns null.

Behavior

  • The 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.

Example

Basic usage: restore saved scopes

import 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
    }
}

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.

Validation

  • There is no client-side validation.
  • toString does not throw.

Behavior

  • The 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.

Example

Basic usage: log the tokens safely

import 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', ...}
    }
}