OAuthTokens

View as Markdown

OAuthTokens

OAuthTokens holds the tokens and user details of one Open Authorization (OAuth) sign-in, in the Contentstack.Management.Core.Models namespace.

When to Use This Class: Read it to get the access token, the refresh token, or the organization of the signed-in user. For example, pass the access token to another tool.

Conceptual Role: Acts as the record that a ContentstackClient stores per client ID. ExchangeCodeForTokenAsync and RefreshTokenAsync of OAuthHandler create it.

Returns: OAuthTokens. The tokens of one OAuth sign-in.

Class-Level Properties

NameTypeRequiredDefaultDescription
AccessTokenstring?NonullAccess token the client sends as authorization: Bearer.
RefreshTokenstring?NonullToken that gets a new access token.
ExpiresAtDateTimeNoDateTime.MinValueUTC time the access token stops being valid.
OrganizationUidstring?NonullUID of the organization the user authorized.
UserUidstring?NonullUID of the signed-in user.
ClientIdstring?NonullClient ID of the app.
AppIdstring?NonullApp UID of the app.
IsExpiredboolRead-onlytruetrue when ExpiresAt is unset or in the past.
NeedsRefreshboolRead-onlytruetrue when ExpiresAt is unset or less than five minutes away.
IsValidboolRead-onlyfalsetrue when AccessToken has a value and IsExpired is false.

Class-Level Notes

Where the times come from.

  • The SDK sets ExpiresAt to the current UTC time plus the expires_in seconds of the token response, minus 60 seconds. IsExpired therefore turns true one minute before the API stops accepting the token.
  • An async request method refreshes the client's access token first when NeedsRefresh is true. A sync method does not.

Changing the stored record.

  • GetOAuthTokens and OAuthHandler.GetCurrentTokens return the stored object itself. A change to its properties changes what the client stores, but not the access token the client sends. The token setters of OAuthHandler behave the same way.

Method Index

OAuthTokens has no methods. Read its properties.

Class-Level Snippet

This snippet signs in with OAuth and prints when the access token expires and whether it needs a refresh.

using System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;

ContentstackClient client = new ContentstackClient();
OAuthHandler oauth = client.OAuth(new OAuthOptions() { AppId = "<APP_ID>", ClientId = "<CLIENT_ID>", RedirectUri = "<REDIRECT_URI>" });

try
{
    string authorizationUrl = await oauth.AuthorizeAsync();
    Console.WriteLine($"Open {authorizationUrl}, then paste the code from the redirect.");

    OAuthTokens tokens = await oauth.ExchangeCodeForTokenAsync(Console.ReadLine() ?? "");
    Console.WriteLine($"Organization {tokens.OrganizationUid}, expires {tokens.ExpiresAt:u}, refresh soon: {tokens.NeedsRefresh}");
}
catch (OAuthException e)
{
    Console.WriteLine($"OAuth failed: {e.Message}");
}