---
title: "OAuthHandler"
description: "OAuthHandler"
url: "https://www.contentstack.com/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler"
product: "Contentstack"
doc_type: "guide"
audience:
  - developers
  - admins
version: "current"
last_updated: "2026-11-22"
---

# OAuthHandler

## OAuthHandler

OAuthHandler runs the Open Authorization (OAuth) 2.0 authorization code flow for one app, in the Contentstack.Management.Core namespace.

**When to Use This Class:** Use this class when your tool signs users in through an OAuth app instead of an email and password. The client then sends Content Management API (CMA) requests as that user.

**Conceptual Role:** Acts as the OAuth client of the SDK. It builds the authorization URL, exchanges the authorization code for tokens, and stores the tokens on the ContentstackClient it belongs to. That client then sends the access token on every request.

**Returns:** OAuthHandler. A handler for one OAuth app.

## Instance State

Create a handler with the [OAuth](/docs/developers/sdks/content-management-sdk/dot-net/reference/contentstackclient#contentstackclient-oauth) method of ContentstackClient. The public constructor OAuthHandler(ContentstackClient client, OAuthOptions options) does the same. The handler's methods fall into three stages:

*   Before sign-in, call AuthorizeAsync, then HandleRedirectAsync or ExchangeCodeForTokenAsync, on the same handler instance.
*   After sign-in, call methods that need stored tokens, for example RefreshTokenAsync or LogoutAsync.
*   In every stage, call the token getters and setters, for example GetAccessToken or HasValidTokens.

A method that needs stored tokens throws an OAuthException subclass when the client stores none for the handler's client ID. The Method Index below lists every method.

**Warning:** A PKCE handler keeps the code verifier that AuthorizeAsync creates in the handler instance. A new handler, for example one from a second client.OAuth(...) call, cannot exchange the authorization code and throws OAuthConfigurationException.

## Class-Level Notes

**Two flows, picked by the client secret.**

*   Without ClientSecret in OAuthOptions, the handler uses Proof Key for Code Exchange (PKCE).
*   With ClientSecret, the handler sends the secret with the token exchange and each refresh.

**Where tokens live.**

*   The client stores the tokens in memory, keyed by client ID. Two handlers with the same client ID read the same tokens. Nothing persists across process restarts, so save the refresh token yourself if you need it later.
*   After a token exchange or a refresh, the client sends authorization: Bearer <ACCESS\_TOKEN> on every request instead of an authtoken.

**Automatic refresh.**

*   Before each async request, the client refreshes the access token when it expires in less than five minutes. Sync requests do not refresh it.
*   The automatic refresh builds a new handler from the client ID and app ID only, so it sends no client secret, even when your handler has one. Call [RefreshTokenAsync](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-refreshtokenasync) on your own handler to refresh with the secret.
*   A failed automatic refresh throws OAuthException from the async request method.

**Hosts.**

*   The SDK derives the OAuth hosts from the client's Host. For api.contentstack.io, it sends the authorization page to app.contentstack.com and the token and authorization requests to developerhub-api.contentstack.com. For a host such as eu-api.contentstack.com, it uses eu-app.contentstack.com and eu-developerhub-api.contentstack.com.
*   These requests go to the Developer Hub API, which the CMA reference does not cover.

**Errors.**

*   See the [OAuthException](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthexception) class page for which exception each step throws. A token request that the API rejects throws OAuthException with the ContentstackErrorException as InnerException.

## Class-Level Properties

Property

Type

Access

Default

Description

ClientId

string

Read-only

OAuthOptions.ClientId

Client ID the handler stores tokens under.

AppId

string

Read-only

OAuthOptions.AppId

App UID of the OAuth app.

RedirectUri

string

Read-only

OAuthOptions.RedirectUri

Redirect URI of the app.

UsePkce

bool

Read-only

OAuthOptions.UsePkce

true when the handler uses PKCE.

Scope

string\[\]

Read-only

OAuthOptions.Scope

Scopes the authorization URL requests.

## Capability Matrix

Capability

Supported

Notes / Alternative

Persist tokens across restarts

No

Save GetRefreshToken() yourself, then call RefreshTokenAsync with it in the next process.

Refresh before a sync request

No

Call RefreshTokenAsync, or use async request methods.

Client credentials or other grant types

No

The handler supports the authorization code grant only.

## Method Index

**Sign in.** Available on a new handler. Call them in this order on one handler instance.

Method Name

Returns

Description

[AuthorizeAsync](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-authorizeasync)

The authorization URL to open in a browser.

Builds the URL the user opens to authorize the app.

[HandleRedirectAsync](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-handleredirectasync)

A task that completes when the client holds the tokens.

Reads the authorization code from the redirect URL and exchanges it.

[ExchangeCodeForTokenAsync](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-exchangecodefortokenasync)

The new access and refresh tokens.

Exchanges an authorization code for tokens.

**Keep the session.** Available on a handler whose client stores tokens.

Method Name

Returns

Description

[RefreshTokenAsync](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-refreshtokenasync)

The new access and refresh tokens.

Gets a new access token with a refresh token.

[Logout](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-logout)

The logout confirmation text.

Revokes the app authorization and clears the tokens.

[LogoutAsync](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-logoutasync)

The logout confirmation text.

Revokes the app authorization and clears the tokens asynchronously.

**Read the stored tokens.** Available on every handler.

Method Name

Returns

Description

[GetCurrentTokens](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-getcurrenttokens)

The stored tokens for the handler's client ID.

Reads the whole token record.

[HasTokens](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-hastokens)

True when the client holds tokens for the handler's client ID.

Checks for stored tokens.

[HasValidTokens](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-hasvalidtokens)

True when the client holds an unexpired access token.

Checks for a usable access token.

[GetAccessToken](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-getaccesstoken)

The stored access token.

Reads the access token.

[GetRefreshToken](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-getrefreshtoken)

The stored refresh token.

Reads the refresh token.

[GetOrganizationUID](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-getorganizationuid)

The UID of the authorized organization.

Reads the organization UID.

[GetUserUID](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-getuseruid)

The UID of the signed-in user.

Reads the user UID.

[GetTokenExpiryTime](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-gettokenexpirytime)

The UTC expiry time of the access token.

Reads the expiry time.

**Change the stored tokens.** Available on every handler.

Method Name

Returns

Description

[SetAccessToken](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-setaccesstoken)

This method returns nothing.

Stores an access token.

[SetRefreshToken](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-setrefreshtoken)

This method returns nothing.

Stores a refresh token.

[SetOrganizationUID](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-setorganizationuid)

This method returns nothing.

Stores an organization UID.

[SetUserUID](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-setuseruid)

This method returns nothing.

Stores a user UID.

[SetTokenExpiryTime](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-settokenexpirytime)

This method returns nothing.

Stores an expiry time.

[ClearTokens](/docs/developers/sdks/content-management-sdk/dot-net/reference/oauthhandler#oauthhandler-cleartokens)

This method returns nothing.

Removes the stored tokens of this app.

## Class-Level Snippet

This snippet signs in with the PKCE flow, lists the user's organizations as the OAuth user, and signs out.

```
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
{
    Console.WriteLine($"Open {await oauth.AuthorizeAsync()}, then paste the URL you are redirected to.");
    await oauth.HandleRedirectAsync(Console.ReadLine() ?? "");

    ContentstackResponse response = await client.Organization().GetOrganizationsAsync();
    Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());

    await oauth.LogoutAsync();
}
catch (OAuthException e)
{
    Console.WriteLine($"OAuth failed: {e.Message}");
}
catch (ContentstackErrorException e)
{
    Console.WriteLine($"Request failed: {(int)e.StatusCode} {e.ErrorCode} {e.ErrorMessage}");
}
```

## Methods

Each method of the OAuthHandler class has its own section below, with its parameters, validation rules, behavior, and examples.

## AuthorizeAsync

AuthorizeAsync builds the URL that the user opens in a browser to authorize the Open Authorization (OAuth) app.

This method takes no parameters.

```
Returns: Task<string>. The authorization URL to open in a browser.
ValidationThrows OAuthAuthorizationException if the SDK cannot build the URL, for example when the client's Host is not a valid host name.The handler's options passed validation when you created it, so AuthorizeAsync runs no other checks.BehaviorClient-side only. AuthorizeAsync sends no request, and the returned task is already complete.Builds the URL from the client's Host, with api replaced by app and a .io ending replaced by .com, so api.contentstack.io becomes app.contentstack.com.Adds response_type, client_id, redirect_uri, and, when Scope has values, a space-separated scope parameter.For a PKCE handler, creates a new code verifier, keeps it in the handler, and adds code_challenge and code_challenge_method=S256. Each call replaces the earlier verifier, so exchange the authorization code from the latest URL.The URL places the query string before the #!/apps/<APP_ID>/authorize fragment, in the form https://app.contentstack.com:443/?response_type=code&client_id=...#!/apps/<APP_ID>/authorize.ExampleBasic usage: print the authorization URLusing 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 this URL to authorize the app: {authorizationUrl}");
}
catch (OAuthAuthorizationException e)
{
    // Thrown when the SDK cannot build the URL
    Console.WriteLine($"OAuth failed: {e.Message}");
}All parameters: request scopes with a client secretusing System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;

ContentstackClient client = new ContentstackClient(new ContentstackClientOptions() { Host = "eu-api.contentstack.com" });
OAuthHandler oauth = client.OAuth(new OAuthOptions()
{
    AppId = "<APP_ID>",
    ClientId = "<CLIENT_ID>",
    ClientSecret = "<CLIENT_SECRET>",
    RedirectUri = "<REDIRECT_URI>",
    Scope = new string[] { "cm.stacks.management:read" }
});

try
{
    // Points to eu-app.contentstack.com, with no code challenge
    Console.WriteLine(await oauth.AuthorizeAsync());
}
catch (OAuthAuthorizationException e)
{
    Console.WriteLine(e.Message);
}
```

## ClearTokens

ClearTokens removes the token record that the client stores for this app.

This method takes no parameters.

```
Returns: void. This method returns nothing.
ValidationThere is no client-side validation. Calling it when the client holds no tokens raises no error.BehaviorClient-side only. ClearTokens sends no request, so the API does not revoke the tokens. Call Logout to revoke the app authorization.Does not change what the client sends. A client that sends an Open Authorization (OAuth) access token keeps sending it. Call the ClearOAuthTokens method of ContentstackClient to stop that as well.ExampleBasic usage: forget the stored tokensusing System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Models;

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

oauth.SetRefreshToken("<REFRESH_TOKEN>");
oauth.ClearTokens();
Console.WriteLine(oauth.HasTokens());
```

## ExchangeCodeForTokenAsync

ExchangeCodeForTokenAsync exchanges an authorization code for an access token and a refresh token, and makes the client send the access token on every request.

```
Returns: Task<OAuthTokens>. The new access and refresh tokens.
ValidationThrows ArgumentException if authorizationCode is null or empty. The method is async, so the exception surfaces when you await the task.Throws OAuthConfigurationException if the handler uses PKCE and AuthorizeAsync has not run on this handler instance, because the token request needs the code verifier.Throws OAuthException when the token endpoint rejects the request, for example for a used or expired authorization code. The ContentstackErrorException from the API is the InnerException.BehaviorSends one POST /token request to the Developer Hub host, for example https://developerhub-api.contentstack.com/token, as a form with grant_type=authorization_code, code, redirect_uri, client_id, and either code_verifier or client_secret.
Stores the tokens on the client under the handler's client ID, then sets the client's Authtoken to the access token and IsOAuthToken to true.Sets ExpiresAt to the current UTC time plus the expires_in seconds of the response, minus 60 seconds.The Content Management API (CMA) reference does not cover this request. It belongs to the Developer Hub API.HandleRedirectAsync reads the authorization code from a redirect URL and calls ExchangeCodeForTokenAsync for you.ExampleBasic usage: exchange the code from the redirectusing 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
{
    Console.WriteLine($"Open {await oauth.AuthorizeAsync()}, then paste the code from the redirect.");
    OAuthTokens tokens = await oauth.ExchangeCodeForTokenAsync(Console.ReadLine() ?? "");
    Console.WriteLine($"Signed in as {tokens.UserUid}");
}
catch (OAuthException e) when (e.InnerException is ContentstackErrorException apiError)
{
    // Thrown when the token endpoint rejects the code
    Console.WriteLine($"Request failed: {(int)apiError.StatusCode} {apiError.ErrorCode} {apiError.ErrorMessage}");
}
catch (OAuthException e)
{
    Console.WriteLine($"OAuth failed: {e.Message}");
}Edge case: exchanging a code on a new handlerusing 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>" });

await oauth.AuthorizeAsync();

// A second handler has no code verifier from AuthorizeAsync.
OAuthHandler other = client.OAuth(new OAuthOptions() { AppId = "<APP_ID>", ClientId = "<CLIENT_ID>", RedirectUri = "<REDIRECT_URI>" });

try
{
    await other.ExchangeCodeForTokenAsync("<AUTHORIZATION_CODE>");
}
catch (OAuthConfigurationException e)
{
    // Fires before any request, because this handler never ran AuthorizeAsync
    Console.WriteLine(e.Message);
}
```

The code value from the redirect URL.

## GetAccessToken

GetAccessToken returns the access token that the client stores for this app.

This method takes no parameters.

```
Returns: string. The stored access token.
ValidationThere is no client-side validation. Returns null when the client holds no tokens. It does not throw.BehaviorClient-side only. GetAccessToken reads the token record that the client stores for the handler's client ID, and sends no request.Returns the stored value even when it has expired. Check HasValidTokens first.ExampleBasic usage: read the value after a refreshusing 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
{
    await oauth.RefreshTokenAsync("<REFRESH_TOKEN>");
    string accessToken = oauth.GetAccessToken();
    Console.WriteLine(accessToken?.Length > 0 ? "Access token stored" : "No access token");
}
catch (OAuthException e)
{
    // Thrown when the refresh request fails
    Console.WriteLine($"OAuth failed: {e.Message}");
}
```

## GetCurrentTokens

GetCurrentTokens returns the whole token record that the client stores for this app.

This method takes no parameters.

```
Returns: OAuthTokens. The stored tokens for the handler's client ID.
ValidationThere is no client-side validation. Returns null when the client holds no tokens. It does not throw.BehaviorClient-side only. GetCurrentTokens reads the token record that the client stores for the handler's client ID, and sends no request.Returns the stored object itself. A change to its properties changes the stored record, but not the access token the client sends. See the OAuthTokens class page.ExampleBasic usage: read the value after a refreshusing 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
{
    await oauth.RefreshTokenAsync("<REFRESH_TOKEN>");
    OAuthTokens tokens = oauth.GetCurrentTokens();
    Console.WriteLine($"{tokens?.UserUid} in {tokens?.OrganizationUid}");
}
catch (OAuthException e)
{
    // Thrown when the refresh request fails
    Console.WriteLine($"OAuth failed: {e.Message}");
}
```

## GetOrganizationUID

GetOrganizationUID returns the UID of the organization the user authorized the app for.

This method takes no parameters.

```
Returns: string. The UID of the authorized organization.
ValidationThere is no client-side validation. Returns null when the client holds no tokens. It does not throw.BehaviorClient-side only. GetOrganizationUID reads the token record that the client stores for the handler's client ID, and sends no request.The value comes from the organization_uid of the token response.ExampleBasic usage: read the value after a refreshusing 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
{
    await oauth.RefreshTokenAsync("<REFRESH_TOKEN>");
    Console.WriteLine(oauth.GetOrganizationUID());
}
catch (OAuthException e)
{
    // Thrown when the refresh request fails
    Console.WriteLine($"OAuth failed: {e.Message}");
}
```

## GetRefreshToken

GetRefreshToken returns the refresh token that the client stores for this app.

This method takes no parameters.

```
Returns: string. The stored refresh token.
ValidationThere is no client-side validation. Returns null when the client holds no tokens. It does not throw.BehaviorClient-side only. GetRefreshToken reads the token record that the client stores for the handler's client ID, and sends no request.Save the value if you need to resume the session in a later process, then pass it to RefreshTokenAsync.ExampleBasic usage: read the value after a refreshusing 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
{
    await oauth.RefreshTokenAsync("<REFRESH_TOKEN>");
    string refreshToken = oauth.GetRefreshToken();
    Console.WriteLine(refreshToken?.Length > 0 ? "Refresh token stored" : "No refresh token");
}
catch (OAuthException e)
{
    // Thrown when the refresh request fails
    Console.WriteLine($"OAuth failed: {e.Message}");
}
```

## GetTokenExpiryTime

GetTokenExpiryTime returns the UTC time at which the SDK treats the stored access token as expired.

This method takes no parameters.

```
Returns: Nullable<DateTime>. The UTC expiry time of the access token.
ValidationThere is no client-side validation. Returns null when the client holds no tokens. It does not throw.BehaviorClient-side only. GetTokenExpiryTime reads the token record that the client stores for the handler's client ID, and sends no request.The SDK sets the time to the token response's expires_in seconds from the moment it stored the tokens, minus 60 seconds.ExampleBasic usage: read the value after a refreshusing 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
{
    await oauth.RefreshTokenAsync("<REFRESH_TOKEN>");
    Console.WriteLine($"Expires at {oauth.GetTokenExpiryTime():u}");
}
catch (OAuthException e)
{
    // Thrown when the refresh request fails
    Console.WriteLine($"OAuth failed: {e.Message}");
}
```

## GetUserUID

GetUserUID returns the UID of the user who authorized the app.

This method takes no parameters.

```
Returns: string. The UID of the signed-in user.
ValidationThere is no client-side validation. Returns null when the client holds no tokens. It does not throw.BehaviorClient-side only. GetUserUID reads the token record that the client stores for the handler's client ID, and sends no request.The value comes from the user_uid of the token response.ExampleBasic usage: read the value after a refreshusing 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
{
    await oauth.RefreshTokenAsync("<REFRESH_TOKEN>");
    Console.WriteLine(oauth.GetUserUID());
}
catch (OAuthException e)
{
    // Thrown when the refresh request fails
    Console.WriteLine($"OAuth failed: {e.Message}");
}
```

## HandleRedirectAsync

HandleRedirectAsync reads the authorization code from the URL the app redirected to, and exchanges it for tokens.

```
Returns: Task. A task that completes when the client holds the tokens.
ValidationThrows ArgumentException if url is null or empty. The method is async, so the exception surfaces when you await the task.Throws OAuthException if url is not an absolute URL or has no code query parameter.Throws the exceptions that ExchangeCodeForTokenAsync throws, including OAuthException when the token endpoint rejects the authorization code.BehaviorSplits the query string of url into name and value pairs and reads code. The method skips a pair whose value holds an unencoded =.Calls ExchangeCodeForTokenAsync with the authorization code. The tokens are on the client when the task completes, and the method returns no value. Call GetCurrentTokens to read them.ExampleBasic usage: finish sign-in from the redirect URLusing 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
{
    Console.WriteLine($"Open {await oauth.AuthorizeAsync()}, then paste the URL you are redirected to.");
    await oauth.HandleRedirectAsync(Console.ReadLine() ?? "");
    Console.WriteLine(oauth.HasValidTokens());
}
catch (OAuthException e) when (e.InnerException is ContentstackErrorException apiError)
{
    // Thrown when the token endpoint rejects the code
    Console.WriteLine($"Request failed: {(int)apiError.StatusCode} {apiError.ErrorCode} {apiError.ErrorMessage}");
}
catch (OAuthException e)
{
    // Thrown when the URL holds no code
    Console.WriteLine($"OAuth failed: {e.Message}");
}
catch (ArgumentException e)
{
    Console.WriteLine(e.Message);
}
```

The full redirect URL, with its code parameter.

## HasTokens

HasTokens checks whether the client stores tokens for this app, whether or not they have expired.

This method takes no parameters.

```
Returns: bool. True when the client holds tokens for the handler's client ID.
ValidationThere is no client-side validation. It does not throw.BehaviorClient-side only. HasTokens reads the token record that the client stores for the handler's client ID, and sends no request.Returns true for expired tokens too. Call HasValidTokens to check for a usable access token.ExampleBasic usage: read the value after a refreshusing 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
{
    await oauth.RefreshTokenAsync("<REFRESH_TOKEN>");
    Console.WriteLine(oauth.HasTokens());
}
catch (OAuthException e)
{
    // Thrown when the refresh request fails
    Console.WriteLine($"OAuth failed: {e.Message}");
}
```

## HasValidTokens

HasValidTokens checks whether the client stores an unexpired access token for this app.

This method takes no parameters.

```
Returns: bool. True when the client holds an unexpired access token.
ValidationThere is no client-side validation. Returns false when the client holds no tokens. It does not throw.BehaviorClient-side only. HasValidTokens reads the token record that the client stores for the handler's client ID, and sends no request.Returns the IsValid property of the stored OAuthTokens: an access token with an ExpiresAt later than the current UTC time. The SDK sets ExpiresAt 60 seconds early.ExampleBasic usage: read the value after a refreshusing 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
{
    await oauth.RefreshTokenAsync("<REFRESH_TOKEN>");
    Console.WriteLine(oauth.HasValidTokens());
}
catch (OAuthException e)
{
    // Thrown when the refresh request fails
    Console.WriteLine($"OAuth failed: {e.Message}");
}
```

## Logout

Logout revokes the user's authorization of the Open Authorization (OAuth) app and removes the stored tokens.

This method takes no parameters.

```
Returns: string. The logout confirmation text.
ValidationThrows InvalidOperationException if the client stores no tokens for the handler's client ID, with the OAuthException as InnerException.A failed revocation request raises no error. Logout still removes the stored tokens.Warning: Logout ends the user's authorization of the app. Every access and refresh token from it stops working, and the user must authorize the app again.
BehaviorSends up to two requests to the Developer Hub host with the access token:GET /manifests/<APP_ID>/authorizations, with the organization_uid header, to find the authorization of the signed-in user.DELETE /manifests/<APP_ID>/authorizations/<AUTHORIZATION_UID> to revoke it.After the revocation request, the SDK clears the client's Authtoken and sets IsOAuthToken to false.When the SDK cannot find the authorization, it skips the revocation, and the client keeps sending the access token. Call the ClearOAuthTokens method of ContentstackClient to stop it.Returns the text Logged out successfully in every case that does not throw.Blocks the calling thread while the requests run.ExampleBasic usage: sign outusing 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
{
    await oauth.RefreshTokenAsync("<REFRESH_TOKEN>");
    Console.WriteLine(oauth.Logout());
}
catch (InvalidOperationException e)
{
    // Thrown when the client holds no tokens for the app
    Console.WriteLine($"Logout failed: {e.Message}");
}
catch (OAuthException e)
{
    Console.WriteLine($"OAuth failed: {e.Message}");
}
```

## LogoutAsync

LogoutAsync revokes the user's authorization of the Open Authorization (OAuth) app and removes the stored tokens, without blocking the calling thread.

This method takes no parameters.

```
Returns: Task<string>. The logout confirmation text.
ValidationThrows OAuthException if the client stores no tokens for the handler's client ID. LogoutAsync throws OAuthException here, while Logout throws InvalidOperationException.Throws InvalidOperationException if clearing the tokens fails for another reason.A failed revocation request raises no error.Warning: LogoutAsync ends the user's authorization of the app. Every access and refresh token from it stops working.
BehaviorOtherwise behaves like Logout.ExampleBasic usage: sign outusing 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
{
    await oauth.RefreshTokenAsync("<REFRESH_TOKEN>");
    Console.WriteLine(await oauth.LogoutAsync());
}
catch (OAuthException e)
{
    // Thrown when the client holds no tokens or the refresh fails
    Console.WriteLine($"OAuth failed: {e.Message}");
}Edge case: sign out without a sessionusing 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
{
    await oauth.LogoutAsync();
}
catch (OAuthException e)
{
    // Fires before any request, because the client stores no tokens for the app
    Console.WriteLine(e.Message);
}
```

## RefreshTokenAsync

RefreshTokenAsync gets a new access token with a refresh token, and makes the client send the new access token.

```
Returns: Task<OAuthTokens>. The new access and refresh tokens.
ValidationThrows OAuthTokenRefreshException if refreshToken is empty and the client stores no refresh token for the handler's client ID. The method is async, so the exception surfaces when you await the task.Throws OAuthException when the token endpoint rejects the request, for example for a revoked refresh token. The ContentstackErrorException from the API is the InnerException.BehaviorSends one POST /token request to the Developer Hub host as a form with grant_type=refresh_token, refresh_token, client_id, and client_secret for a handler with a client secret.
Stores the new tokens on the client and sets the client's Authtoken to the new access token. When the response has no new refresh token, the SDK keeps the one it sent.Works without AuthorizeAsync, so you can resume a session in a new process with a refresh token you saved.The client also refreshes automatically before an async request, without the client secret. See the OAuthHandler class page.ExampleBasic usage: refresh the stored access tokenusing 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
{
    OAuthTokens tokens = await oauth.RefreshTokenAsync();
    Console.WriteLine($"New token expires at {tokens.ExpiresAt:u}");
}
catch (OAuthException e) when (e.InnerException is ContentstackErrorException apiError)
{
    // Thrown when the token endpoint rejects the refresh token
    Console.WriteLine($"Request failed: {(int)apiError.StatusCode} {apiError.ErrorCode} {apiError.ErrorMessage}");
}
catch (OAuthException e)
{
    // OAuthTokenRefreshException when no refresh token is stored
    Console.WriteLine($"OAuth failed: {e.Message}");
}All parameters: resume a session with a saved refresh tokenusing 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
{
    await oauth.RefreshTokenAsync("<REFRESH_TOKEN>");

    ContentstackResponse response = await client.GetUserAsync();
    Console.WriteLine(response.OpenJsonObjectResponse().ToJsonString());
}
catch (OAuthException e)
{
    Console.WriteLine(e.Message);
}
catch (ContentstackErrorException e)
{
    Console.WriteLine(e.ErrorMessage);
}
```

Refresh token to use. Uses the stored one when null.

## SetAccessToken

SetAccessToken stores an access token in the token record that the client keeps for this app.

```
Returns: void. This method returns nothing.
ValidationThrows ArgumentException (parameter token) if token is null or empty, because an empty value would leave the record unusable.BehaviorClient-side only. SetAccessToken sends no request.Creates a token record for the handler's client ID when none exists, then sets the one value.Does not change the access token the client sends. Only ExchangeCodeForTokenAsync and RefreshTokenAsync switch the client to a new access token.To make the client send a saved access token, create it with new ContentstackClientOptions() { Authtoken = "<ACCESS_TOKEN>", IsOAuthToken = true } instead.ExampleBasic usage: restore a saved valueusing System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Models;

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

oauth.SetAccessToken("<ACCESS_TOKEN>");
Console.WriteLine(oauth.HasTokens());
```

Access token to store.

## SetOrganizationUID

SetOrganizationUID stores an organization UID in the token record that the client keeps for this app.

```
Returns: void. This method returns nothing.
ValidationThrows ArgumentException (parameter organizationUID) if organizationUID is null or empty, because an empty value would leave the record unusable.BehaviorClient-side only. SetOrganizationUID sends no request.Creates a token record for the handler's client ID when none exists, then sets the one value.Does not change the access token the client sends. Only ExchangeCodeForTokenAsync and RefreshTokenAsync switch the client to a new access token.Logout sends this value as the organization_uid header.ExampleBasic usage: restore a saved valueusing System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Models;

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

oauth.SetOrganizationUID("<ORGANIZATION_UID>");
Console.WriteLine(oauth.HasTokens());
```

UID of the authorized organization.

## SetRefreshToken

SetRefreshToken stores a refresh token in the token record that the client keeps for this app.

```
Returns: void. This method returns nothing.
ValidationThrows ArgumentException (parameter token) if token is null or empty, because an empty value would leave the record unusable.BehaviorClient-side only. SetRefreshToken sends no request.Creates a token record for the handler's client ID when none exists, then sets the one value.Does not change the access token the client sends. Only ExchangeCodeForTokenAsync and RefreshTokenAsync switch the client to a new access token.RefreshTokenAsync without an argument reads the stored refresh token.ExampleBasic usage: restore a saved valueusing System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Models;

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

oauth.SetRefreshToken("<REFRESH_TOKEN>");
Console.WriteLine(oauth.HasTokens());
```

Refresh token to store.

## SetTokenExpiryTime

SetTokenExpiryTime stores an access token expiry time in the token record that the client keeps for this app.

```
Returns: void. This method returns nothing.
ValidationThrows ArgumentException (parameter expiryTime) if expiryTime is default(DateTime), because an empty value would leave the record unusable.BehaviorClient-side only. SetTokenExpiryTime sends no request.Creates a token record for the handler's client ID when none exists, then sets the one value.Does not change the access token the client sends. Only ExchangeCodeForTokenAsync and RefreshTokenAsync switch the client to a new access token.Pass a UTC time, because the SDK compares the value with DateTime.UtcNow.ExampleBasic usage: restore a saved valueusing System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Models;

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

oauth.SetTokenExpiryTime(DateTime.UtcNow.AddHours(1));
Console.WriteLine(oauth.HasTokens());
```

UTC time the access token expires.

## SetUserUID

SetUserUID stores a user UID in the token record that the client keeps for this app.

```
Returns: void. This method returns nothing.
ValidationThrows ArgumentException (parameter userUID) if userUID is null or empty, because an empty value would leave the record unusable.BehaviorClient-side only. SetUserUID sends no request.Creates a token record for the handler's client ID when none exists, then sets the one value.Does not change the access token the client sends. Only ExchangeCodeForTokenAsync and RefreshTokenAsync switch the client to a new access token.Logout uses this value to find the user's authorization.ExampleBasic usage: restore a saved valueusing System;
using Contentstack.Management.Core;
using Contentstack.Management.Core.Models;

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

oauth.SetUserUID("<USER_UID>");
Console.WriteLine(oauth.HasTokens());
```

UID of the signed-in user.

## OAuthHandler | .NET Management SDK | Contentstack

The OAuthHandler class in the .NET Management SDK runs the OAuth 2.0 authorization code flow, stores the tokens on the client, refreshes them, and signs out.