OAuthHandler
OAuthHandler
OAuthHandler runs the Open Authorization (OAuth) sign-in of a Java Management SDK client and holds its tokens. Use this class to
- build the URL where the user signs in
- exchange the authorization code from the redirect for tokens
- refresh, read, restore or clear the tokens
Get the handler with the getOAuthHandler method of a client that you build with setOAuth or setOAuthConfig. getOAuthHandler returns null for a client without OAuth. The class also has a public constructor, new OAuthHandler(OkHttpClient, OAuthConfig), but no client uses a handler that you create that way.
authorize
authorize builds the URL of the Contentstack page where the user signs in and approves the app.
Returns: String. The authorization URL to open in a browser.
Validation
- There is no client-side validation of the configuration at this call. The client checked it when you built it.
- Throws IllegalArgumentException if the configuration holds an authEndpoint that is not a valid HTTPS URL.
Behavior
- The URL carries response_type, client_id, redirect_uri and app_id, plus scope when the configuration holds scopes.
- In Proof Key for Code Exchange (PKCE) mode, without a client secret, authorize also adds code_challenge and code_challenge_method=S256. It calculates the challenge from the verifier of this handler.
- authorize does not add a state parameter.
- authorize sends no request. Open the URL in a browser. After sign-in, Contentstack redirects to the redirect URI with the authorization code in the code query parameter.
- Exchange that authorization code with the exchangeCodeForToken method of this same handler. In PKCE mode, another client has another verifier, so its exchange fails.
- The getOAuthAuthorizationUrl method of Contentstack returns the same URL.
Example
Basic usage: print the sign-in URL
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.oauth.OAuthHandler;
public class PrintSignInUrl {
public static void main(String[] args) {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
OAuthHandler oauthHandler = client.getOAuthHandler();
String url = oauthHandler.authorize();
// Open the URL in a browser. Contentstack redirects to <REDIRECT_URI>?code=...
System.out.println(url);
}
}exchangeCodeForToken
exchangeCodeForToken sends the authorization code from the redirect to the token endpoint and stores the tokens it receives.
| Name | Type | Description |
|---|---|---|
| code (required) | String | Authorization code from the code query parameter of the redirect. |
Returns: CompletableFuture<OAuthTokens>. A future that completes with the new tokens.
Validation
- For a null or blank code, exchangeCodeForToken returns a future that has already failed with IllegalArgumentException, because the token endpoint needs an authorization code.
- Known issue: In 1.16.0 on Java 8, a null or blank code makes exchangeCodeForToken throw NoSuchMethodError, because the SDK calls a method that Java 9 added. Check the authorization code before the call, or run on Java 9 or later.
- A failure does not throw from exchangeCodeForToken. The future completes with an exception, and get() throws ExecutionException. Its cause is a RuntimeException whose own cause holds the reason, such as the API error message or an IOException for a network failure.
- An API rejection of the authorization code fails the future in the same way. The innermost cause message carries the API error message.
Behavior
- One call sends one POST request to the token endpoint of the configuration with a form body. The body carries grant_type=authorization_code, code without leading or trailing spaces, redirect_uri, client_id and app_id.
- With a client secret, the body also carries client_secret. Without one, it carries the PKCE code_verifier of this handler.
- The request runs on a background thread from the common ForkJoinPool. It uses the timeouts and proxy of the client, without the SDK retry.
- On success, the handler stores the tokens, sets their expiry time, and calls onTokensUpdated of the token callback. Every later request of the client sends the new access token.
- The exchangeOAuthCode method of Contentstack calls this method.
Example
Basic usage: sign in and read the organization UID
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.OAuthTokens;
import com.contentstack.cms.oauth.OAuthHandler;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
public class ExchangeCode {
public static void main(String[] args) throws InterruptedException {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
OAuthHandler oauthHandler = client.getOAuthHandler();
System.out.println("Open this URL and sign in: " + oauthHandler.authorize());
System.out.print("Paste the code from the redirect URI: ");
String code = new Scanner(System.in).nextLine();
try {
OAuthTokens tokens = oauthHandler.exchangeCodeForToken(code).get();
System.out.println("Signed in to organization " + tokens.getOrganizationUid());
} catch (ExecutionException e) {
// The exchange failed. The innermost cause holds the API error message or the network error.
Throwable cause = e.getCause();
while (cause.getCause() != null) {
cause = cause.getCause();
}
System.out.println("Sign-in failed: " + cause.getMessage());
}
}
}Non-blocking: handle the tokens in a callback
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.oauth.OAuthHandler;
public class ExchangeCodeAsync {
public static void main(String[] args) {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
OAuthHandler oauthHandler = client.getOAuthHandler();
String code = args[0]; // the code query parameter from the redirect
oauthHandler.exchangeCodeForToken(code)
.thenAccept(tokens -> System.out.println("User: " + tokens.getUserUid()))
.exceptionally(error -> {
System.out.println("Sign-in failed: " + error.getMessage());
return null;
})
.join();
}
}getAccessToken
getAccessToken returns the access token that the client sends with its requests.
Returns: String. The current access token, or null.
Validation
- There is no client-side validation.
- getAccessToken does not throw.
Behavior
- Returns null before sign-in and after logout.
- The value is a secret. Do not log it.
Example
Basic usage: check for an access token after sign-in
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.oauth.OAuthHandler;
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();
OAuthHandler oauthHandler = client.getOAuthHandler();
System.out.println("Open this URL and sign in: " + oauthHandler.authorize());
System.out.print("Paste the code from the redirect URI: ");
String code = new Scanner(System.in).nextLine();
try {
oauthHandler.exchangeCodeForToken(code).get();
} catch (ExecutionException e) {
System.out.println("Sign-in failed: " + e.getCause().getMessage());
return;
}
System.out.println(oauthHandler.getAccessToken() != null ? "Signed in" : "Not signed in");
}
}getCodeChallenge
getCodeChallenge returns the Proof Key for Code Exchange (PKCE) challenge that authorize put in the authorization URL.
Returns: String. The PKCE code challenge, or null.
Validation
- There is no client-side validation.
- getCodeChallenge does not throw.
Behavior
- Returns null until the first authorize call, and always null with a client secret.
- The challenge is the SHA-256 hash of the verifier, Base64 URL-encoded without padding.
Example
Basic usage: read the value
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.oauth.OAuthHandler;
public class ReadCodeChallenge {
public static void main(String[] args) {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
OAuthHandler oauthHandler = client.getOAuthHandler();
oauthHandler.authorize();
System.out.println(oauthHandler.getCodeChallenge());
}
}getCodeVerifier
getCodeVerifier returns the Proof Key for Code Exchange (PKCE) verifier that the handler sends in the code exchange.
Returns: String. The PKCE code verifier, or null.
Validation
- There is no client-side validation.
- getCodeVerifier does not throw.
Behavior
- The handler creates a random 96-character verifier when it starts, only when the configuration has no client secret. With a client secret, the value is null.
- The verifier stays the same for the life of the handler. A new client has a new verifier.
- Treat the value as a secret.
Example
Basic usage: read the value
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.oauth.OAuthHandler;
public class ReadCodeVerifier {
public static void main(String[] args) {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
OAuthHandler oauthHandler = client.getOAuthHandler();
System.out.println(oauthHandler.getCodeVerifier() != null ? "PKCE verifier ready" : "Client secret mode");
}
}getConfig
getConfig returns the Open Authorization (OAuth) configuration that you gave the client.
Returns: OAuthConfig. The OAuth configuration of the client.
Validation
- There is no client-side validation.
- getConfig does not throw.
Behavior
- With the setOAuth method of Contentstack.Builder, the SDK builds the configuration for you, and this method is the way to read it.
- The OAuthConfig class lists its values.
Example
Basic usage: read the value
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.OAuthConfig;
import com.contentstack.cms.oauth.OAuthHandler;
public class ReadConfig {
public static void main(String[] args) {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
OAuthHandler oauthHandler = client.getOAuthHandler();
OAuthConfig config = oauthHandler.getConfig();
System.out.println(config.getTokenEndpoint());
}
}getOauthAppAuthorization
getOauthAppAuthorization requests the authorization status of the app for the signed-in user.
Returns: CompletableFuture<OAuthTokens>. A future that completes with the parsed status response.
Validation
- There is no client-side validation.
- A failure does not throw from getOauthAppAuthorization. The future completes with an exception, and get() throws ExecutionException. Its cause is a RuntimeException whose own cause holds the reason, such as the API error message or an IOException for a network failure.
- A response body that is not JSON also fails the future.
Behavior
- One call sends one GET request to the authorization page URL of the configuration plus /status, with the access token in the Authorization header.
- The SDK reads the response body into an OAuthTokens object and does not store it on the handler.
- Known issue: In 1.16.0, the SDK builds this URL from the authorization page URL, which contains a # fragment. OkHttp does not send the fragment, so the request goes to the root of the Contentstack app host (for example https://app.contentstack.com/), not to an authorization endpoint. Do not rely on this method for the authorization status.
Example
Basic usage: request the authorization status
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.OAuthTokens;
import com.contentstack.cms.oauth.OAuthHandler;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
public class RequestAuthorizationStatus {
public static void main(String[] args) throws InterruptedException {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
OAuthHandler oauthHandler = client.getOAuthHandler();
System.out.println("Open this URL and sign in: " + oauthHandler.authorize());
System.out.print("Paste the code from the redirect URI: ");
String code = new Scanner(System.in).nextLine();
try {
oauthHandler.exchangeCodeForToken(code).get();
} catch (ExecutionException e) {
System.out.println("Sign-in failed: " + e.getCause().getMessage());
return;
}
try {
OAuthTokens status = oauthHandler.getOauthAppAuthorization().get();
System.out.println(status);
} catch (ExecutionException e) {
System.out.println("Status request failed: " + e.getCause().getMessage());
}
}
}getOrganizationUID
getOrganizationUID returns the UID of the organization that the user authorized the app for.
Returns: String. The organization UID from the tokens, or null.
Validation
- There is no client-side validation.
- getOrganizationUID does not throw.
Behavior
- Returns null before sign-in, or when the token response carried no organization_uid.
Example
Basic usage: open the authorized organization
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.oauth.OAuthHandler;
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();
OAuthHandler oauthHandler = client.getOAuthHandler();
System.out.println("Open this URL and sign in: " + oauthHandler.authorize());
System.out.print("Paste the code from the redirect URI: ");
String code = new Scanner(System.in).nextLine();
try {
oauthHandler.exchangeCodeForToken(code).get();
} catch (ExecutionException e) {
System.out.println("Sign-in failed: " + e.getCause().getMessage());
return;
}
String organizationUid = oauthHandler.getOrganizationUID();
if (organizationUid != null) {
Organization organization = client.organization(organizationUid);
System.out.println("Organization: " + organizationUid);
}
}
}getRefreshToken
getRefreshToken returns the refresh token that the SDK uses to get a new access token.
Returns: String. The current refresh token, or null.
Validation
- There is no client-side validation.
- getRefreshToken does not throw.
Behavior
- Returns null before sign-in, after logout, or when the token response carried no refresh token.
- The value is a secret. Store it securely if you save it.
Example
Basic usage: save the refresh token
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.oauth.OAuthHandler;
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();
OAuthHandler oauthHandler = client.getOAuthHandler();
System.out.println("Open this URL and sign in: " + oauthHandler.authorize());
System.out.print("Paste the code from the redirect URI: ");
String code = new Scanner(System.in).nextLine();
try {
oauthHandler.exchangeCodeForToken(code).get();
} catch (ExecutionException e) {
System.out.println("Sign-in failed: " + e.getCause().getMessage());
return;
}
String refreshToken = oauthHandler.getRefreshToken();
if (refreshToken != null) {
// Save refreshToken in your secret store
System.out.println("Refresh token available");
}
}
}getState
getState returns the Open Authorization (OAuth) state value of the handler.
Returns: String. The state value, always null.
Validation
- There is no client-side validation.
- getState does not throw.
Behavior
- Returns null in 1.16.0. No SDK method sets the value.
- authorize does not add a state parameter to the authorization URL.
Example
Basic usage: read the value
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.oauth.OAuthHandler;
public class ReadState {
public static void main(String[] args) {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
OAuthHandler oauthHandler = client.getOAuthHandler();
System.out.println(oauthHandler.getState()); // null
}
}getTokens
getTokens returns the tokens that the handler holds.
Returns: OAuthTokens. The current tokens, or null.
Validation
- There is no client-side validation.
- getTokens does not throw.
Behavior
- Returns null before sign-in and after logout.
- Returns the stored object, not a copy. A setter you call on it changes the tokens that the client sends.
- The getOAuthTokens method of Contentstack returns the same object.
Example
Basic usage: read the stored tokens
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.OAuthTokens;
import com.contentstack.cms.oauth.OAuthHandler;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
public class ReadStoredTokens {
public static void main(String[] args) throws InterruptedException {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
OAuthHandler oauthHandler = client.getOAuthHandler();
System.out.println("Open this URL and sign in: " + oauthHandler.authorize());
System.out.print("Paste the code from the redirect URI: ");
String code = new Scanner(System.in).nextLine();
try {
oauthHandler.exchangeCodeForToken(code).get();
} catch (ExecutionException e) {
System.out.println("Sign-in failed: " + e.getCause().getMessage());
return;
}
OAuthTokens tokens = oauthHandler.getTokens();
System.out.println(tokens); // the tokens, with the secrets hidden
}
}getUserUID
getUserUID returns the UID of the user who signed in.
Returns: String. The user UID from the tokens, or null.
Validation
- There is no client-side validation.
- getUserUID does not throw.
Behavior
- Returns null before sign-in, or when the token response carried no user_uid.
Example
Basic usage: read the user UID
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.oauth.OAuthHandler;
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();
OAuthHandler oauthHandler = client.getOAuthHandler();
System.out.println("Open this URL and sign in: " + oauthHandler.authorize());
System.out.print("Paste the code from the redirect URI: ");
String code = new Scanner(System.in).nextLine();
try {
oauthHandler.exchangeCodeForToken(code).get();
} catch (ExecutionException e) {
System.out.println("Sign-in failed: " + e.getCause().getMessage());
return;
}
System.out.println("Signed in as " + oauthHandler.getUserUID());
}
}hasValidAccessToken
hasValidAccessToken reports whether the handler holds an access token that is more than two minutes from expiry.
Returns: boolean. True when an unexpired access token is present.
Validation
- There is no client-side validation.
- hasValidAccessToken does not throw.
Behavior
- Returns false before sign-in, after logout, and when the access token expires within two minutes.
- false does not stop requests. The SDK refreshes the token before the next request when the tokens hold a refresh token.
Example
Basic usage: check before a batch of requests
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.oauth.OAuthHandler;
public class CheckAccessToken {
public static void main(String[] args) {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
OAuthHandler oauthHandler = client.getOAuthHandler();
if (!oauthHandler.hasValidAccessToken()) {
System.out.println("Sign in first: " + oauthHandler.authorize());
}
}
}logout
logout removes the tokens from the handler, and can first ask Contentstack to revoke the app authorization.
| Name | Type | Description |
|---|---|---|
| revokeAuthorization (required) | boolean | true also sends a revoke request before clearing the tokens. |
Returns: CompletableFuture<Void>. A future that completes after the handler clears the tokens.
Validation
- There is no client-side validation.
- With revokeAuthorization set to true, a failed revoke request fails the future, and the handler keeps its tokens. get() then throws ExecutionException.
- Known issue: In 1.16.0, logout does not call onTokensCleared of the token callback. Remove your saved tokens after the future completes.
Behavior
- The work runs on a background thread from the common ForkJoinPool.
- With false, logout sends no request. It only removes the tokens from the handler.
- With true and tokens present, logout first calls revokeOauthAppAuthorization and waits for it. See the Known issue on that method.
- After logout, every request of the client throws IOException from execute() until you sign in again.
- The oauthLogout method of Contentstack calls this method.
Example
Basic usage: sign out and clear saved tokens
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.oauth.OAuthHandler;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
public class SignOut {
public static void main(String[] args) throws InterruptedException {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
OAuthHandler oauthHandler = client.getOAuthHandler();
System.out.println("Open this URL and sign in: " + oauthHandler.authorize());
System.out.print("Paste the code from the redirect URI: ");
String code = new Scanner(System.in).nextLine();
try {
oauthHandler.exchangeCodeForToken(code).get();
} catch (ExecutionException e) {
System.out.println("Sign-in failed: " + e.getCause().getMessage());
return;
}
try {
oauthHandler.logout(false).get();
// logout does not call onTokensCleared, so clear your saved tokens here
System.out.println(oauthHandler.getTokens()); // null
} catch (ExecutionException e) {
System.out.println("Logout failed: " + e.getCause().getMessage());
}
}
}refreshAccessToken
refreshAccessToken gets a new access token with the refresh token, when the current access token expires within two minutes.
Returns: CompletableFuture<OAuthTokens>. A future that completes with the current or new tokens.
Validation
- When the handler holds no refresh token, refreshAccessToken returns a future that has already failed with IllegalStateException, because a refresh needs one.
- Known issue: In 1.16.0 on Java 8, refreshAccessToken throws NoSuchMethodError in that case, because the SDK calls a method that Java 9 added. Check hasValidAccessToken and the refresh token first, or run on Java 9 or later.
- A failure does not throw from refreshAccessToken. The future completes with an exception, and get() throws ExecutionException. Its cause is a RuntimeException whose own cause holds the reason, such as the API error message or an IOException for a network failure.
Behavior
- When the access token is more than two minutes from expiry, the future completes with the current tokens and the SDK sends no request.
- Otherwise one call sends one POST request to the token endpoint with a form body. The body carries grant_type=refresh_token, refresh_token, client_id, app_id, and the client secret or the PKCE verifier of this handler.
- When the response carries no refresh token, the SDK keeps the earlier one.
- On success, the handler stores the tokens and calls onTokensUpdated of the token callback.
- The SDK also calls this method before a request when the access token is about to expire, and after a 401 response. Call it yourself only to refresh ahead of time.
Example
Basic usage: refresh after a long pause
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.OAuthTokens;
import com.contentstack.cms.oauth.OAuthHandler;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
public class RefreshTokens {
public static void main(String[] args) throws InterruptedException {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
OAuthHandler oauthHandler = client.getOAuthHandler();
System.out.println("Open this URL and sign in: " + oauthHandler.authorize());
System.out.print("Paste the code from the redirect URI: ");
String code = new Scanner(System.in).nextLine();
try {
oauthHandler.exchangeCodeForToken(code).get();
} catch (ExecutionException e) {
System.out.println("Sign-in failed: " + e.getCause().getMessage());
return;
}
try {
OAuthTokens tokens = oauthHandler.refreshAccessToken().get();
System.out.println("Access token valid until " + tokens.getExpiresAt());
} catch (ExecutionException e) {
// No refresh token, or the token endpoint rejected the refresh
System.out.println("Refresh failed: " + e.getCause().getMessage());
}
}
}revokeOauthAppAuthorization
revokeOauthAppAuthorization asks Contentstack to revoke the authorization that the user gave the app.
Returns: CompletableFuture<Void>. A future that completes when the request finishes.
Validation
- There is no client-side validation.
- A failure does not throw from revokeOauthAppAuthorization. The future completes with an exception, and get() throws ExecutionException. Its cause is a RuntimeException whose own cause holds the reason, such as the API error message or an IOException for a network failure.
Behavior
- One call sends one POST request to the authorization page URL of the configuration plus /revoke. The form body carries app_id and client_id, and the access token goes in the Authorization header.
- The method does not clear the tokens on the handler. Use logout for that.
- Known issue: In 1.16.0, the SDK builds this URL from the authorization page URL, which contains a # fragment. OkHttp does not send the fragment, so the request goes to the root of the Contentstack app host (for example https://app.contentstack.com/), not to an authorization endpoint. A future that completes normally does not show that Contentstack revoked the authorization. Remove the app authorization from your Contentstack account instead.
Example
Basic usage: send the revoke request
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.oauth.OAuthHandler;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
public class RevokeAuthorization {
public static void main(String[] args) throws InterruptedException {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
OAuthHandler oauthHandler = client.getOAuthHandler();
System.out.println("Open this URL and sign in: " + oauthHandler.authorize());
System.out.print("Paste the code from the redirect URI: ");
String code = new Scanner(System.in).nextLine();
try {
oauthHandler.exchangeCodeForToken(code).get();
} catch (ExecutionException e) {
System.out.println("Sign-in failed: " + e.getCause().getMessage());
return;
}
try {
oauthHandler.revokeOauthAppAuthorization().get();
System.out.println("Revoke request finished");
} catch (ExecutionException e) {
System.out.println("Revoke request failed: " + e.getCause().getMessage());
}
}
}setTokens
setTokens replaces the tokens that the handler holds, for example with tokens that you saved in an earlier run.
| Name | Type | Description |
|---|---|---|
| tokens (required) | OAuthTokens | Tokens the client sends from the next request on. |
Returns: void. This method returns nothing.
Validation
- There is no client-side validation. setTokens(null) removes the tokens, and every request then throws IOException from execute().
- setTokens does not call the token callback.
Behavior
- The next request of the client sends the access token of these tokens.
- When the tokens have passed their expiry time or have none, the SDK refreshes them before the next request. The refresh needs a refresh token.
- In PKCE mode, the refresh sends the verifier of this handler, which differs from the verifier of the run that signed in.
Example
Basic usage: restore saved tokens and send a request
import com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.OAuthTokens;
import com.contentstack.cms.oauth.OAuthHandler;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.Response;
public class RestoreTokens {
public static void main(String[] args) throws IOException {
Contentstack client = new Contentstack.Builder()
.setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
.build();
OAuthHandler oauthHandler = client.getOAuthHandler();
OAuthTokens saved = new OAuthTokens();
saved.setAccessToken(System.getenv("CONTENTSTACK_ACCESS_TOKEN"));
saved.setRefreshToken(System.getenv("CONTENTSTACK_REFRESH_TOKEN"));
saved.setTokenType("Bearer");
saved.setExpiresIn(0L); // expiry unknown, so the SDK refreshes before the first request
oauthHandler.setTokens(saved);
Response<ResponseBody> response = client.organization().find().execute();
if (!response.isSuccessful()) {
// The API rejected the request. The body holds error_message, error_code and errors.
System.out.println("Request failed: " + response.code() + " " + response.errorBody().string());
return;
}
System.out.println(response.body().string());
}
}