Skip to main content

OAuth 2.0 Support

All the SDKs support popular OAuth 2.0 flows and provide utility methods to generate or refresh access tokens. The SDK handles request authentication for the user while the user only needs to provide the required credentials once during client initialization.

In this article, the words "flow" or "grant" refer to the OAuth 2.0 Grant Types as defined here.

For details on configuring supported OAuth 2.0 flows in your API specification, please refer to the OpenAPI documentation. After configuring your OpenAPI specification and generating the SDK, read below to see how you can use the SDKs to authorize API calls.

The currently supported flows include:

  1. Client Credentials Grant
  2. Resource Owner Password Credentials Grant(a.k.a Password Grant)
  3. Authorization Code Grant

Client Credentials Grant

The Client Credentials Grant flow supports:

Client Initialization

You can initialize the client as shown below.

SdkClient client = new SdkClient.Builder()
.OAuthCCGCredentials(
new OAuthCCGModel.Builder(
"OAuthClientId",
"OAuthClientSecret"
)
.Build())
.Build();

This will fetch the OAuth token automatically when any of the endpoints, requiring OAuth 2.0 Client Credentials Grant authentication, are called. If you wish to configure this token-fetching behavior, see Setting Tokens Automatically.

Resource Owner Password Credentials Grant

Client Initialization

You can initialize the client as shown below.

SdkClient client = new SdkClient.Builder()
.OAuthROPCGCredentials(
new OAuthROPCGModel.Builder(
"OAuthClientId",
"OAuthClientSecret",
"OAuthUsername",
"OAuthPassword"
)
.Build())
.Build();

With the Resource Owner Password Credentials Grant, your application must get a token before it can execute an endpoint call.

Authorization Code Grant

1. Client Initialization

SdkClient client = new SdkClient.Builder()
.OAuthACGCredentials(
new OAuthACGModel.Builder(
"OAuthClientId",
"OAuthClientSecret",
"OAuthRedirectUri"
)
.OAuthScopes(
new List<OAuthScopeOAuthACGEnum>
{
OAuthScopeOAuthACGEnum.ReadScope,
})
.Build())
.Build();

Your application must obtain user authorization before it can execute an endpoint call. This authorization includes the following steps:

To obtain user's consent, you must redirect the user to the authorization page. The BuildAuthorizationUrl() method creates the URL to the authorization page. You must have initialized the client with scopes for which you need permission to access.

string authUrl = await client.AuthorizationCodeAuth.BuildAuthorizationUrl();

You might want to send additional query parameters in the URL. For example, you might want a state parameter to correlate requests and responses or a prompt parameter for re-prompting user consent every time access is requested.

string authUrl = await Client.AuthorizationCodeAuth.BuildAuthorizationUrl(
state: "random_state_string",
additionalParameters: new Dictionary<string, object>
{
["prompt"] = "consent"
}
);

3. Handle the OAuth server response

Once the user responds to the consent request, the OAuth 2.0 server redirects the user to the redirect URI specified in the client initialization step.

If the user approves the request, the authorization code will be sent as the code query string:

https://example.com/oauth/callback?code=XXXXXXXXXXXXXXXXXXXXXXXXX

If the user doesn't approve the request, the response contains an error query string:

https://example.com/oauth/callback?error=access_denied

4. Authorize the client using the code

After receiving the authorization code, it can be exchanged for an access token. The access token is an object containing information for authorizing client requests and refreshing the token itself.

var authCode = GetAuthCodeFromRedirectUri()
var authManager = client.OAuthACG;
try
{
OAuthToken token = authManager.FetchToken(authCode);
// re-initialize the client with OAuth token
client = client.ToBuilder()
.OAuthACGCredentials(
client.OAuthACGModel.ToBuilder()
.OAuthToken(token)
.Build())
.Build();
}
catch (ApiException e)
{
// TODO Handle exception
}

Additionally, you need to manage access token lifetime. The SDK provides some utilities to help you.

Setting Tokens Automatically

You can optionally specify callbacks that run whenever the OAuth token is expired/undefined or updated. The following examples use Client Credentials Grant. Note: the names of variables, functions, etc. will differ depending on your API specification.

SdkClient client = new SdkClient.Builder()
.OAuthCCGCredentials(
new OAuthCCGModel.Builder(
"OAuthClientId",
"OAuthClientSecret"
)
.OAuthTokenProvider(async (credentialsManager, token) =>
{
// Add the callback handler to provide a new OAuth token
// It will be triggered whenever the token is undefined or expired
return LoadTokenFromDatabase() ?? await credentialsManager.FetchTokenAsync();
})
.OAuthOnTokenUpdate(token =>
{
// It will be triggered whenever the token gets updated
SaveTokenToDatabase(token);
})
.Build())
.Build();

If needed, your application can also provide an OAuthToken manually. See Setting Tokens Explicitly.

Setting Tokens Explicitly

There are a few operations you may need to do when managing access tokens. The SDK provides utilities to help you. The following examples use Resource Owner Password Credentials Grant. Note: the names of variables, functions, etc. will differ depending on your API specification.

Fetching the token

After initializing the client, get the auth manager for a particular auth scheme. In this example, it would be the OAuthROPCGCredentials property. The FetchToken() method will exchange the user's credentials for an access token. The access token is an object containing information for authorizing client requests and refreshing the token itself.

var authManager = client.OAuthROPCGCredentials;

try
{
OAuthToken token = authManager.FetchToken();
// re-initialize the client with OAuth token
client = client.ToBuilder()
.OAuthROPCGCredentials(
client.OAuthROPCGModel.ToBuilder()
.OAuthToken(token)
.Build())
.Build();
}
catch (ApiException e)
{
// TODO Handle exception
}

The client can now make authorized endpoint calls. It's recommended that you store the access token for reuse.

Refreshing the token

An access token may expire after sometime. If the API supports a refresh token flow, the SDK lets you refresh the token to extend its lifetime.

if (authManager.IsTokenExpired())
{
try
{
OAuthToken token = authManager.RefreshToken();
// re-initialize the client with OAuth token
client = client.ToBuilder()
.OAuthROPCGCredentials(
client.OAuthROPCGModel.ToBuilder()
.OAuthToken(token)
.Build())
.Build();
}
catch (ApiException e)
{
// TODO Handle exception
}
}

If a token expires, an exception will be thrown before the next endpoint call requiring authentication.