OAuthHandler
OAuthHandler
OAuthHandler runs the Open Authorization (OAuth) sign-in of a JavaScript Management SDK client and holds its tokens. Use this class to
- build the URL where the user signs in and approves your app
- exchange the authorization code from the redirect for an access token and a refresh token
- refresh, read, restore or clear the tokens
- revoke the app authorization of the signed-in user
Get a handler from the oauth method of the ContentstackClient class, for example client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' }).
Class-Level Notes
The sign-in flow. The four steps below sign a user in:
- Call authorize and open the URL it resolves to in a browser.
- The user signs in and approves the app. Contentstack redirects to your redirect URI with the authorization code in the code query parameter.
- Pass the authorization code to exchangeCodeForToken, or pass the whole redirect URL to handleRedirect.
- Send requests with the same client. The SDK adds authorization: Bearer <access token> to every request that includes no authtoken or authorization header.
Proof Key for Code Exchange (PKCE).
- Without a clientSecret, the handler creates a code verifier when you call client.oauth(). authorize sends a challenge calculated from it, and exchangeCodeForToken sends the verifier.
- In Node.js the verifier lives only in that handler object. Call authorize and exchangeCodeForToken on the same handler. A handler from another client.oauth() call has another verifier, so its exchange fails.
- In a browser, the SDK also keeps the verifier in sessionStorage for 10 minutes, under a key that the SDK builds from appId, clientId and redirectUri. A handler created after the redirect with the same three values reuses it. The SDK removes the stored verifier after an exchange, whether it succeeds or fails.
- With a clientSecret, the handler skips PKCE and sends the secret instead.
Token storage.
- The handler stores the tokens on the client, in client.axiosInstance.oauth, not on the handler. Every handler of one client reads and writes the same tokens.
- Each client.oauth() call overwrites the stored appId, clientId and redirectUri of the client.
- The SDK stores the expiry time as the current time plus expires_in minus 60 seconds, in milliseconds.
Hosts.
- The sign-in page uses the app host that matches the API host of the client, for example app.contentstack.com for api.contentstack.io and eu-app.contentstack.com for the eu region.
- Token and authorization requests go to the Developer Hub host, for example developerhub-api.contentstack.com or eu-developerhub-api.contentstack.com.
- A client created with endpoint uses that endpoint as the host of the sign-in page.
Default headers after OAuth requests.
- Known issue: exchangeCodeForToken, refreshAccessToken and handleRedirect replace the default headers of the client with a form Content-Type. Later requests then send JSON bodies as form data, and lose the X-User-Agent and User-Agent headers. Save client.axiosInstance.defaults.headers before the call and assign it back after the call resolves.
- getOauthAppAuthorization, revokeOauthAppAuthorization and logout replace the default headers of the client with authorization, organization_uid and Content-type: application/json. After logout, the client keeps sending the revoked access token. Create a new client to sign in again.
Expired access tokens.
- Known issue: When the stored access token has expired, the next request of the client never completes. Refresh the token before getTokenExpiryTime passes. After it passes, call setTokenExpiryTime with a time in the future, then call refreshAccessToken.
Rate limiting and retry.
- The token, authorization and revoke requests use the request queue of the client. The retry settings of the client apply to them.
Additional Resource For more information on the retry settings and their defaults, refer to the Contentstack documentation.
Capability Matrix
| Capability | Supported | Notes / Alternative |
|---|---|---|
| Send scope or redirect_uri in the authorization URL | No | authorize sends only response_type=code, client_id and, with PKCE, the challenge. Configure scopes in the app |
| Refresh an expired token automatically | No | Call refreshAccessToken before getTokenExpiryTime passes |
| Keep the default headers of the client after a token request | No | Save client.axiosInstance.defaults.headers and assign it back |
Method Index
The four groups below follow the sign-in: start and end it, manage the app authorization, work with the stored tokens, and create PKCE values. Every method is available on the handler that client.oauth() returns.
Sign in and sign out. Available on client.oauth(). These methods build the sign-in URL, get and refresh the tokens, and clear them.
| Method Name | Returns | Description |
|---|---|---|
| authorize | The authorization URL to open in a browser. | Builds the URL that starts the sign-in. |
| exchangeCodeForToken | The token response from Developer Hub. | Exchanges the authorization code for tokens. |
| handleRedirect | This method resolves to nothing. | Exchanges the authorization code from a redirect URL. |
| refreshAccessToken | The token response with the new access token. | Gets a new access token. |
| logout | The text Logged out successfully. | Revokes the authorization and clears the tokens. |
Manage the app authorization. Available on client.oauth(). These methods send requests about the authorization that the user gave the app.
| Method Name | Returns | Description |
|---|---|---|
| getOauthAppAuthorization | The authorization UID of the signed-in user. | Finds the authorization of the current user. |
| revokeOauthAppAuthorization | The API response of the revoke request. | Revokes one app authorization. |
Read and restore the tokens. Available on client.oauth(). These methods read or replace the tokens that the client stores. They send no request.
| Method Name | Returns | Description |
|---|---|---|
| getAccessToken | The access token, or undefined. | Returns the stored access token. |
| getRefreshToken | The refresh token, or null. | Returns the stored refresh token. |
| getOrganizationUID | The organization UID, or null. | Returns the stored organization UID. |
| getUserUID | The user UID, or null. | Returns the stored user UID. |
| getTokenExpiryTime | The expiry time in milliseconds, or null. | Returns the stored expiry time. |
| setAccessToken | This method returns nothing. | Stores an access token. |
| setRefreshToken | This method returns nothing. | Stores a refresh token. |
| setOrganizationUID | This method returns nothing. | Stores an organization UID. |
| setUserUID | This method returns nothing. | Stores a user UID. |
| setTokenExpiryTime | This method returns nothing. | Stores the expiry time. |
Create PKCE values. Available on client.oauth(). These methods calculate values on the client and send no request.
| Method Name | Returns | Description |
|---|---|---|
| generateCodeVerifier | A random code verifier. | Creates a PKCE code verifier. |
| generateCodeChallenge | The code challenge for the verifier. | Calculates a PKCE code challenge. |
Class-Level Snippet
The snippet below signs a user in with PKCE, restores the default headers, and lists the organizations of the user.
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
console.log('Open this URL and sign in:', await oauthHandler.authorize())
// Pass the authorization code from the redirect URI on the command line: node signin.mjs <code>
const code = process.argv[2]
try {
const savedHeaders = client.axiosInstance.defaults.headers
await oauthHandler.exchangeCodeForToken(code)
client.axiosInstance.defaults.headers = savedHeaders
const organizations = await client.organization().fetchAll()
organizations.items.forEach((organization) => console.log(organization.uid, organization.name))
} catch (error) {
// The request failed. The error carries status, error and errorMessage from the response.
console.error(error.status, error.error, error.errorMessage)
}Methods
Each method of the OAuthHandler class has its own section below, with its parameters, validation rules, behavior, and examples.
authorize
authorize builds the URL of the Contentstack page where the user signs in and approves your app.
This method takes no parameters.
Returns: Promise<string>. The authorization URL to open in a browser.
Validation
- There is no client-side validation of the app ID or client ID.
- The returned promise rejects with TypeError when the app host is not a valid URL. A client with an endpoint that is not an absolute URL causes this.
Behavior
- Client-side only. authorize sends no request. Open the URL in a browser.
- The URL points at #!/apps/<appId>/authorize on the app host of the client and carries response_type=code and client_id.
- Without a clientSecret, authorize also adds code_challenge and code_challenge_method=S256. It calculates the challenge from the code verifier of this handler.
- authorize always sends response_type=code, whatever responseType you passed to client.oauth(). It does not send scope, redirect_uri or state.
- After sign-in, Contentstack redirects to the redirect URI of the app with the authorization code in the code query parameter. Exchange the authorization code on this same handler with exchangeCodeForToken or handleRedirect.
Example
Basic usage: print the sign-in URL
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
try {
const url = await oauthHandler.authorize()
// Open the URL in a browser. Contentstack redirects to <REDIRECT_URI>?code=...
console.log(url)
} catch (error) {
// The app host of the client does not form a valid URL
console.error(error.message)
}Build the URL for an app with a client secret
import contentstack from '@contentstack/management'
const client = contentstack.client({ region: 'eu' })
const oauthHandler = client.oauth({
appId: '<APP_ID>',
clientId: '<CLIENT_ID>',
redirectUri: '<REDIRECT_URI>',
clientSecret: '<CLIENT_SECRET>'
})
try {
// With a client secret, the URL has no code_challenge
console.log(await oauthHandler.authorize())
} catch (error) {
console.error(error.message)
}exchangeCodeForToken
exchangeCodeForToken exchanges the authorization code from the redirect for an access token and a refresh token, and stores them on the client.
| Name | Type | Description |
|---|---|---|
| code (required) | string | Authorization code from the code query parameter. |
Returns: Promise<OAuthResponse>. The token response from Developer Hub.
Validation
- There is no client-side validation. exchangeCodeForToken sends code as it is, even when it is empty.
- The returned promise rejects with an Error when Developer Hub rejects the request. The error carries status and statusText, and error, errorMessage and errorCode from the response body.
Additional Resource Refer to Content Management API Errors for the full error code list.
Behavior
- Sends POST /token to the Developer Hub host of the client. The form body holds grant_type=authorization_code, code, redirect_uri and client_id.
- The body also holds client_secret when the handler has one, else the PKCE code_verifier.
- On success, stores access_token, refresh_token, organization_uid, user_uid and the expiry time on the client. Every later request of the client sends the access token as authorization: Bearer <token>, unless it carries an authtoken or authorization header.
- Resolves to the response body as it is, for example access_token, refresh_token, expires_in, organization_uid and user_uid.
- In a browser, removes the stored PKCE verifier after the request, whether it succeeds or fails. Start a new sign-in with authorize after a failed exchange.
- exchangeCodeForToken replaces the default headers of the client. The OAuthHandler page describes the effect and the workaround.
Example
Basic usage: exchange the authorization code and restore the default headers
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
console.log('Open this URL and sign in:', await oauthHandler.authorize())
// Pass the authorization code from the redirect URI on the command line: node exchange.mjs <code>
const code = process.argv[2]
try {
const savedHeaders = client.axiosInstance.defaults.headers
const tokens = await oauthHandler.exchangeCodeForToken(code)
client.axiosInstance.defaults.headers = savedHeaders
console.log(tokens.expires_in, tokens.organization_uid)
} catch (error) {
// Developer Hub rejected the request. The error carries status, error and errorMessage.
console.error(error.status, error.error, error.errorMessage)
}generateCodeChallenge
generateCodeChallenge calculates the Proof Key for Code Exchange (PKCE) code challenge for a code verifier.
| Name | Type | Description |
|---|---|---|
| codeVerifier (required) | string | Code verifier to hash. |
Returns: Promise<string>. The code challenge for the verifier.
Validation
- There is no client-side validation of the verifier format.
- In Node.js, the returned promise rejects with TypeError when codeVerifier is undefined or null, because the hash function needs a string.
Behavior
- Client-side only. generateCodeChallenge sends no request.
- Hashes the verifier with SHA-256 and encodes the hash as URL-safe Base64 without padding, the S256 method of PKCE.
- In a browser with the Web Crypto API, it uses window.crypto.subtle. Otherwise it uses the Node.js crypto module.
- authorize calls it with the verifier of the handler and stores the result on the handler. Call it yourself only when you build the authorization URL without the SDK.
Example
Basic usage: calculate the challenge for the verifier of the handler
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
try {
const challenge = await oauthHandler.generateCodeChallenge(oauthHandler.codeVerifier)
console.log(challenge)
} catch (error) {
// Thrown when the verifier is missing, for example on a handler with a client secret
console.error(error.message)
}generateCodeVerifier
generateCodeVerifier creates a random Proof Key for Code Exchange (PKCE) code verifier.
| Name | Type | Description |
|---|---|---|
| length | number | Number of characters in the verifier. |
Returns: string. A random code verifier.
Validation
- There is no client-side validation. generateCodeVerifier does not enforce the 43 to 128 character range of PKCE. A length of 0 or less returns an empty string.
Behavior
- Client-side only. generateCodeVerifier sends no request.
- Picks each character from the letters, digits and the four characters -, ., _ and ~, with Math.random.
- Returns a new value and does not store it. The handler creates its own verifier when you call client.oauth() without a clientSecret, and authorize and exchangeCodeForToken use that one, not the value that this method returns.
Example
Basic usage: create a verifier and its challenge
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
const verifier = oauthHandler.generateCodeVerifier()
const challenge = await oauthHandler.generateCodeChallenge(verifier)
console.log(verifier.length, challenge)All parameters: create a 64-character verifier
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
const verifier = oauthHandler.generateCodeVerifier(64)
console.log(verifier.length)getAccessToken
getAccessToken returns the access token that the client stores.
This method takes no parameters.
Returns: string. The access token, or undefined.
Validation
- There is no client-side validation. getAccessToken never throws.
Behavior
- Client-side only. getAccessToken sends no request.
- Reads the value from the token storage of the client, which every handler of the client shares.
- Returns undefined when the client stores no access token, for example before sign-in or after logout.
- exchangeCodeForToken, refreshAccessToken and setAccessToken store the value.
Example
Basic usage: check for a stored access token
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
const accessToken = oauthHandler.getAccessToken()
console.log(accessToken === undefined ? 'No access token' : 'Access token stored')getOauthAppAuthorization
getOauthAppAuthorization finds the authorization that the signed-in user gave the app and returns its UID.
This method takes no parameters.
Returns: Promise<string>. The authorization UID of the signed-in user.
Validation
- There is no client-side validation of the stored values.
- The returned promise rejects with an Error when the app has no authorizations, or none of them belongs to the stored user UID.
- The returned promise rejects with an Error when Developer Hub rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the response.
Additional Resource Refer to Content Management API Errors for the full error code list.
Behavior
- Sends GET /manifests/<appId>/authorizations to the Developer Hub host, with the stored access token as authorization: Bearer <token> and the stored organization UID as the organization_uid header.
- Reads the data array of the response, keeps the items whose user.uid matches the stored user UID, and resolves to the authorization_uid of the first one.
- Replaces the default headers of the client with authorization, organization_uid and Content-type: application/json. Later requests of the client send these headers.
Example
Basic usage: find the authorization of the signed-in user
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
oauthHandler.setAccessToken('<ACCESS_TOKEN>')
oauthHandler.setOrganizationUID('<ORGANIZATION_UID>')
oauthHandler.setUserUID('<USER_UID>')
try {
const authorizationId = await oauthHandler.getOauthAppAuthorization()
console.log(authorizationId)
} catch (error) {
// Developer Hub rejected the request, or the user has no authorization for the app
console.error(error.status, error.errorCode, error.errorMessage || error.message)
}getOrganizationUID
getOrganizationUID returns the organization UID that the client stores from the token response.
This method takes no parameters.
Returns: string. The organization UID, or null.
Validation
- There is no client-side validation. getOrganizationUID never throws.
Behavior
- Client-side only. getOrganizationUID sends no request.
- Reads the value from the token storage of the client, which every handler of the client shares.
- Returns null when the client stores no organization UID.
- exchangeCodeForToken and setOrganizationUID store the value. getOauthAppAuthorization sends it as the organization_uid header.
Example
Basic usage: read the organization of the signed-in user
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
const organizationUid = oauthHandler.getOrganizationUID()
console.log(organizationUid)getRefreshToken
getRefreshToken returns the refresh token that the client stores.
This method takes no parameters.
Returns: string. The refresh token, or null.
Validation
- There is no client-side validation. getRefreshToken never throws.
Behavior
- Client-side only. getRefreshToken sends no request.
- Reads the value from the token storage of the client, which every handler of the client shares.
- Returns null when the client stores no refresh token.
- exchangeCodeForToken, refreshAccessToken and setRefreshToken store the value. Save it to restore the session later with setRefreshToken.
Example
Basic usage: read the refresh token to save it
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
const refreshToken = oauthHandler.getRefreshToken()
console.log(refreshToken)getTokenExpiryTime
getTokenExpiryTime returns the time at which the SDK treats the stored access token as expired.
This method takes no parameters.
Returns: number. The expiry time in milliseconds, or null.
Validation
- There is no client-side validation. getTokenExpiryTime never throws.
Behavior
- Client-side only. getTokenExpiryTime sends no request.
- Reads the value from the token storage of the client, which every handler of the client shares.
- Returns null when the client stores no expiry time.
- The value is a timestamp in milliseconds, like Date.now(). After a token request, it is the time of the response plus expires_in minus 60 seconds. Refresh the token with refreshAccessToken before this time passes.
Example
Basic usage: print the remaining lifetime of the access token
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
const expiryTime = oauthHandler.getTokenExpiryTime()
if (expiryTime !== null) {
console.log('Seconds left:', Math.round((expiryTime - Date.now()) / 1000))
}getUserUID
getUserUID returns the user UID that the client stores from the token response.
This method takes no parameters.
Returns: string. The user UID, or null.
Validation
- There is no client-side validation. getUserUID never throws.
Behavior
- Client-side only. getUserUID sends no request.
- Reads the value from the token storage of the client, which every handler of the client shares.
- Returns null when the client stores no user UID.
- exchangeCodeForToken and setUserUID store the value. getOauthAppAuthorization uses it to find the authorization of the user.
Example
Basic usage: read the UID of the signed-in user
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
const userUid = oauthHandler.getUserUID()
console.log(userUid)handleRedirect
handleRedirect reads the authorization code from the redirect URL and exchanges it for tokens.
| Name | Type | Description |
|---|---|---|
| url (required) | string | Full redirect URL, with the code query parameter. |
Returns: Promise<void>. This method resolves to nothing.
Validation
- The returned promise rejects with TypeError when url is not an absolute URL, because handleRedirect parses it with the URL class.
- The returned promise rejects with an Error when the URL has no code query parameter. handleRedirect sends no request in that case.
- The returned promise rejects with an Error when Developer Hub rejects the exchange. The error carries status and statusText, and error, errorMessage and errorCode from the response body.
Additional Resource Refer to Content Management API Errors for the full error code list.
Behavior
- Calls exchangeCodeForToken with the code value of the URL. The tokens land on the client as they do for that method.
- Resolves to undefined. Read the tokens with getAccessToken and the other getters.
- handleRedirect replaces the default headers of the client, as exchangeCodeForToken does. The OAuthHandler page describes the effect and the workaround.
Example
Basic usage: exchange the authorization code from the redirect URL
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
console.log('Open this URL and sign in:', await oauthHandler.authorize())
// Pass the full URL that the browser was redirected to: node redirect.mjs "<url>"
const redirectUrl = process.argv[2]
try {
const savedHeaders = client.axiosInstance.defaults.headers
await oauthHandler.handleRedirect(redirectUrl)
client.axiosInstance.defaults.headers = savedHeaders
console.log(oauthHandler.getUserUID(), oauthHandler.getOrganizationUID())
} catch (error) {
// Thrown for a URL without a code, or when Developer Hub rejects the exchange
console.error(error.status, error.error, error.message)
}logout
logout revokes the app authorization of the signed-in user and clears the tokens that the client stores.
This method takes no parameters.
Returns: Promise<string>. The text Logged out successfully.
Warning logout revokes the authorization that the user gave the app. The user must sign in and approve the app again, and you cannot undo it.
Validation
- There is no client-side validation.
- The returned promise rejects with an Error when the client stores no authorization for the stored user UID, because getOauthAppAuthorization finds nothing to revoke.
- The returned promise rejects with an Error when Developer Hub rejects a request. The error carries status, statusText, errorMessage, errorCode and errors from the response.
Additional Resource Refer to Content Management API Errors for the full error code list.
Behavior
- Calls getOauthAppAuthorization to find the authorization UID of the stored user, then revokeOauthAppAuthorization with it. That is two requests to the Developer Hub host.
- After both requests succeed, clears every value that the handler stored on the client: tokens, UIDs, expiry time, app ID, client ID and redirect URI.
- The default headers of the client keep the revoked authorization header and the organization_uid header, so later requests of the client still send them. Create a new client to sign in again.
- logout does not end an authtoken session. Use the logout method of the client for that.
Example
Basic usage: sign the user out
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
oauthHandler.setAccessToken('<ACCESS_TOKEN>')
oauthHandler.setOrganizationUID('<ORGANIZATION_UID>')
oauthHandler.setUserUID('<USER_UID>')
try {
const message = await oauthHandler.logout()
console.log(message, oauthHandler.getAccessToken())
} catch (error) {
// A request failed, or the user has no authorization for the app
console.error(error.status, error.errorCode, error.errorMessage || error.message)
}refreshAccessToken
refreshAccessToken gets a new access token with a refresh token and stores it on the client.
| Name | Type | Description |
|---|---|---|
| providedRefreshToken | string | Refresh token to send instead of the stored one. |
Returns: Promise<OAuthResponse>. The token response with the new access token.
Validation
- The returned promise rejects with an Error when you pass no refresh token and the client stores none, because the token request needs one. refreshAccessToken sends no request in that case.
- The returned promise rejects with an Error when Developer Hub rejects the request. The error carries status and statusText, and error, errorMessage and errorCode from the response body.
Additional Resource Refer to Content Management API Errors for the full error code list.
Behavior
- Sends POST /token to the Developer Hub host of the client with a form body: grant_type=refresh_token, refresh_token, and the client_id and redirect_uri that the client stores.
- On success, stores the new access_token and expiry time. It stores the new refresh_token when the response has one, else it keeps the old one. It does not change the stored organization UID or user UID.
- Resolves to the response body as it is.
- When the stored access token has already expired, the request does not complete. Call setTokenExpiryTime with a time in the future first, as the second example below shows.
- refreshAccessToken replaces the default headers of the client. The OAuthHandler page describes the effect and the workaround.
Example
Basic usage: refresh the token before it expires
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
oauthHandler.setAccessToken('<ACCESS_TOKEN>')
oauthHandler.setRefreshToken('<REFRESH_TOKEN>')
oauthHandler.setTokenExpiryTime(Date.now() + 60000)
try {
const savedHeaders = client.axiosInstance.defaults.headers
const tokens = await oauthHandler.refreshAccessToken()
client.axiosInstance.defaults.headers = savedHeaders
console.log(tokens.expires_in, oauthHandler.getTokenExpiryTime())
} catch (error) {
// Developer Hub rejected the request. The error carries status, error and errorMessage.
console.error(error.status, error.error, error.errorMessage)
}All parameters: refresh after the stored token expired, with a saved refresh token
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
try {
if (oauthHandler.getTokenExpiryTime() !== null && Date.now() > oauthHandler.getTokenExpiryTime()) {
// Move the expiry time forward so the token request itself can start
oauthHandler.setTokenExpiryTime(Date.now() + 60000)
}
const savedHeaders = client.axiosInstance.defaults.headers
const tokens = await oauthHandler.refreshAccessToken('<REFRESH_TOKEN>')
client.axiosInstance.defaults.headers = savedHeaders
console.log(tokens.access_token !== undefined)
} catch (error) {
console.error(error.message)
}revokeOauthAppAuthorization
revokeOauthAppAuthorization revokes one authorization of the app, so its tokens stop working.
| Name | Type | Description |
|---|---|---|
| authorizationId (required) | string | UID of the authorization to revoke. |
Returns: Promise<any>. The API response of the revoke request.
Warning You cannot restore a revoked authorization. The user must sign in and approve the app again.
Validation
- revokeOauthAppAuthorization checks only the length of authorizationId. With undefined, an empty string or a one-character value, it sends no request and resolves to undefined.
- The returned promise rejects with an Error when Developer Hub rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the response.
Additional Resource Refer to Content Management API Errors for the full error code list.
Behavior
- Sends DELETE /manifests/<appId>/authorizations/<authorizationId> to the Developer Hub host, with the stored access token as authorization: Bearer <token> and the stored organization UID as the organization_uid header.
- Resolves to the response body as it is.
- Does not clear the tokens that the client stores. logout revokes the authorization of the signed-in user and clears them.
- Replaces the default headers of the client with authorization, organization_uid and Content-type: application/json.
Example
Basic usage: revoke the authorization of the signed-in user
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
oauthHandler.setAccessToken('<ACCESS_TOKEN>')
oauthHandler.setOrganizationUID('<ORGANIZATION_UID>')
try {
const response = await oauthHandler.revokeOauthAppAuthorization('<AUTHORIZATION_ID>')
console.log(response)
} catch (error) {
// Developer Hub rejected the request. The error carries status, errorCode and errorMessage.
console.error(error.status, error.errorCode, error.errorMessage)
}setAccessToken
setAccessToken stores an access token that you saved earlier, so the client sends it without a new sign-in.
| Name | Type | Description |
|---|---|---|
| token (required) | string | Access token to store. |
Returns: void. This method returns nothing.
Validation
- Throws Error if token is falsy, for example undefined, null, an empty string or 0, because the client needs an access token to store. The stored value stays unchanged.
- setAccessToken does not check the format of the value.
Behavior
- Client-side only. setAccessToken sends no request.
- Writes the value to the token storage of the client, which every handler of the client shares.
- Every later request of the client that carries no authtoken or authorization header sends the token as authorization: Bearer <token>.
Example
Basic usage: restore a saved session
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
try {
oauthHandler.setAccessToken('<ACCESS_TOKEN>')
oauthHandler.setRefreshToken('<REFRESH_TOKEN>')
oauthHandler.setTokenExpiryTime(Date.now() + 60 * 60 * 1000)
console.log(oauthHandler.getAccessToken() !== undefined)
} catch (error) {
// Thrown when the value is empty
console.error(error.message)
}setOrganizationUID
setOrganizationUID stores the organization UID that getOauthAppAuthorization and revokeOauthAppAuthorization send as the organization_uid header.
| Name | Type | Description |
|---|---|---|
| organizationUID (required) | string | Organization UID to store. |
Returns: void. This method returns nothing.
Validation
- Throws Error if organizationUID is falsy, for example undefined, null, an empty string or 0, because the client needs an organization UID to store. The stored value stays unchanged.
- setOrganizationUID does not check the format of the value.
Behavior
- Client-side only. setOrganizationUID sends no request.
- Writes the value to the token storage of the client, which every handler of the client shares.
- Set it when you restore a saved session and plan to call logout.
Example
Basic usage: restore the organization of a saved session
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
try {
oauthHandler.setOrganizationUID('<ORGANIZATION_UID>')
console.log(oauthHandler.getOrganizationUID())
} catch (error) {
// Thrown when the value is empty
console.error(error.message)
}setRefreshToken
setRefreshToken stores a refresh token, which refreshAccessToken sends when you pass none.
| Name | Type | Description |
|---|---|---|
| token (required) | string | Refresh token to store. |
Returns: void. This method returns nothing.
Validation
- Throws Error if token is falsy, for example undefined, null, an empty string or 0, because the client needs a refresh token to store. The stored value stays unchanged.
- setRefreshToken does not check the format of the value.
Behavior
- Client-side only. setRefreshToken sends no request.
- Writes the value to the token storage of the client, which every handler of the client shares.
- refreshAccessToken reads the stored value when you call it without an argument.
Example
Basic usage: store a saved refresh token before refreshing
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
try {
oauthHandler.setRefreshToken('<REFRESH_TOKEN>')
console.log(oauthHandler.getRefreshToken())
} catch (error) {
// Thrown when the value is empty
console.error(error.message)
}setTokenExpiryTime
setTokenExpiryTime stores the time at which the SDK treats the stored access token as expired.
| Name | Type | Description |
|---|---|---|
| expiryTime (required) | number | Expiry timestamp in milliseconds, like Date.now(). |
Returns: void. This method returns nothing.
Validation
- Throws Error if expiryTime is falsy, for example undefined, null, an empty string or 0, because the client needs an expiry time to store. The stored value stays unchanged.
- setTokenExpiryTime does not check the format of the value.
Behavior
- Client-side only. setTokenExpiryTime sends no request.
- Writes the value to the token storage of the client, which every handler of the client shares.
- Before each request, the SDK compares the stored value with Date.now(). Pass a timestamp in milliseconds. A Date object also compares correctly, but getTokenExpiryTime then returns the Date.
Example
Basic usage: store the expiry time of a saved session
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
try {
// The saved token stays valid for one more hour
oauthHandler.setTokenExpiryTime(Date.now() + 60 * 60 * 1000)
console.log(new Date(oauthHandler.getTokenExpiryTime()).toISOString())
} catch (error) {
// Thrown when the value is empty
console.error(error.message)
}setUserUID
setUserUID stores the user UID that getOauthAppAuthorization uses to find the authorization of the user.
| Name | Type | Description |
|---|---|---|
| userUID (required) | string | User UID to store. |
Returns: void. This method returns nothing.
Validation
- Throws Error if userUID is falsy, for example undefined, null, an empty string or 0, because the client needs a user UID to store. The stored value stays unchanged.
- setUserUID does not check the format of the value.
Behavior
- Client-side only. setUserUID sends no request.
- Writes the value to the token storage of the client, which every handler of the client shares.
- Set it when you restore a saved session and plan to call logout.
Example
Basic usage: restore the user of a saved session
import contentstack from '@contentstack/management'
const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })
try {
oauthHandler.setUserUID('<USER_UID>')
console.log(oauthHandler.getUserUID())
} catch (error) {
// Thrown when the value is empty
console.error(error.message)
}