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:
- Client Credentials Grant
- Resource Owner Password Credentials Grant(a.k.a Password Grant)
- Authorization Code Grant
Client Credentials Grant
The Client Credentials Grant flow supports:
- Automatic Token Refresh
- Callback for Token Expiry or Token Update Events
Client Initialization
You can initialize the client as shown below.
- .NET
- Java
- Python
- Ruby
- TypeScript
- PHP
- Go
SdkClient client = new SdkClient.Builder()
.OAuthCCGCredentials(
new OAuthCCGModel.Builder(
"OAuthClientId",
"OAuthClientSecret"
)
.Build())
.Build();
SdkClient client = new SdkClient.Builder()
.clientCredentialsAuth(new ClientCredentialsAuthModel.Builder(
"OAuthClientId",
"OAuthClientSecret"
)
.build())
.build();
from sdk.http.auth.o_auth_2 import ClientCredentialsAuthCredentials
from sdk.sdk_client import SdkClient
client = SdkClient(
client_credentials_auth_credentials=ClientCredentialsAuthCredentials(
o_auth_client_id='OAuthClientId',
o_auth_client_secret='OAuthClientSecret'
)
)
require 'sdk'
include Sdk
client = Client.new(
client_credentials_auth_credentials: ClientCredentialsAuthCredentials.new(
o_auth_client_id: 'OAuthClientId',
o_auth_client_secret: 'OAuthClientSecret'
)
)
const client = new Client({
clientCredentialsAuthCredentials: {
oAuthClientId: 'OAuthClientId',
oAuthClientSecret: 'OAuthClientSecret',
},
});
$client = SdkClientBuilder::init()
->clientCredentialsAuthCredentials(
ClientCredentialsAuthCredentialsBuilder::init(
'OAuthClientId',
'OAuthClientSecret'
)
)
->build();
import (
"sdk"
)
// ...
client := sdk.NewClient(
sdk.CreateConfiguration(
sdk.WithClientCredentialsAuthCredentials(
sdk.NewClientCredentialsAuthCredentials(
"OAuthClientId",
"OAuthClientSecret",
),
),
),
)
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.
- .NET
- Java
- Python
- Ruby
- TypeScript
- PHP
- Go
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.
SdkClient client = new SdkClient.Builder()
.resourceOwnerAuth(new ResourceOwnerAuthModel.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.
from sdk.models.o_auth_scope_enum import OAuthScopeEnum
from sdk.http.auth.o_auth_2 import ResourceOwnerAuthCredentials
from sdk.sdk_client import SdkClient
client = SdkClient(
resource_owner_auth_credentials=ResourceOwnerAuthCredentials(
o_auth_client_id="OAuthClientId",
o_auth_client_secret="OAuthClientSecret",
o_auth_username="OAuthUsername",
o_auth_password="OAuthPassword"
),
)
With the Resource Owner Password Credentials Grant, your application must get a token before it can execute an endpoint call.
require 'sdk'
include Sdk
client = Client.new(
resource_owner_auth_credentials: ResourceOwnerAuthCredentials.new(
o_auth_client_id: 'OAuthClientId',
o_auth_client_secret: 'OAuthClientSecret',
o_auth_username: 'OAuthUsername',
o_auth_password: 'OAuthPassword'
),
)
With the Resource Owner Password Credentials Grant, your application must get a token before it can execute an endpoint call.
const client = new Client({
resourceOwnerAuthCredentials: {
oAuthClientId: 'OAuthClientId',
oAuthClientSecret: 'OAuthClientSecret',
oAuthUsername: 'OAuthUsername',
oAuthPassword: 'OAuthPassword',
}
});
This will fetch the OAuth token automatically when any of the endpoints, requiring OAuth 2.0 Resource Owner Password Credentials Grant authentication, are called. If you wish to configure this token-fetching behavior, see Setting Tokens Automatically.
$client = SdkClientBuilder::init()
->resourceOwnerAuthCredentials(
ResourceOwnerAuthCredentialsBuilder::init(
'OAuthClientId',
'OAuthClientSecret',
'OAuthUsername',
'OAuthPassword'
)
)
->build();
This will fetch the OAuth token automatically when any of the endpoints, requiring OAuth 2.0 Resource Owner Password Credentials Grant authentication, are called. If you wish to configure this token-fetching behavior, see Setting Tokens Automatically.
client := sdk.NewClient(
sdk.CreateConfiguration(
sdk.WithResourceOwnerAuthCredentials(
sdk.NewResourceOwnerAuthCredentials(
"OAuthClientId",
"OAuthClientSecret",
"OAuthUsername",
"OAuthPassword",
),
),
),
)
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
- .NET
- Java
- Python
- Ruby
- TypeScript
- PHP
- Go
SdkClient client = new SdkClient.Builder()
.OAuthACGCredentials(
new OAuthACGModel.Builder(
"OAuthClientId",
"OAuthClientSecret",
"OAuthRedirectUri"
)
.OAuthScopes(
new List<OAuthScopeOAuthACGEnum>
{
OAuthScopeOAuthACGEnum.ReadScope,
})
.Build())
.Build();
SdkClient client = new SdkClient.Builder()
.authorizationCodeAuth(new AuthorizationCodeAuthModel.Builder(
"OAuthClientId",
"OAuthClientSecret",
"OAuthRedirectUri"
)
.oAuthScopes(Arrays.asList(
OAuthScopeEnum.READ_SCOPE,
OAuthScopeEnum.WRITE_SCOPE
))
.build())
.build();
from sdk.models.o_auth_token import OAuthToken
from sdk.models.o_auth_scope_enum import OAuthScopeEnum
from sdk.exceptions.api_exception import APIException
from sdk.http.auth.o_auth_2 import AuthorizationCodeAuthCredentials
from sdk.configuration import Environment
from sdk.sdk_client import SdkClient
client = SdkClient(
authorization_code_auth_credentials=AuthorizationCodeAuthCredentials(
o_auth_client_id='OAuthClientId',
o_auth_client_secret='OAuthClientSecret',
o_auth_redirect_uri='OAuthRedirectUri',
o_auth_scopes=[
OAuthScopeEnum.READ_SCOPE,
OAuthScopeEnum.WRITE_SCOPE
]
)
)
require 'sdk'
include Sdk
client = Client.new(
authorization_code_auth_credentials: AuthorizationCodeAuthCredentials.new(
o_auth_client_id: 'OAuthClientId',
o_auth_client_secret: 'OAuthClientSecret',
o_auth_redirect_uri: 'OAuthRedirectUri',
o_auth_scopes: [
OAuthScopeEnum::READ_SCOPE,
OAuthScopeEnum::WRITE_SCOPE
]
),
)
const client = new Client({
authorizationCodeAuthCredentials: {
oAuthClientId: 'OAuthClientId',
oAuthClientSecret: 'OAuthClientSecret',
oAuthRedirectUri: 'OAuthRedirectUri',
oAuthScopes: [
OAuthScopeEnum.ReadScope,
OAuthScopeEnum.WriteScope
]
},
});
$client = SdkClient::init()
->authorizationCodeAuthCredentials(
AuthorizationCodeAuthCredentialsBuilder::init(
'OAuthClientId',
'OAuthClientSecret',
'OAuthRedirectUri'
)
->oAuthScopes(
[
OAuthScopeEnum::READ_SCOPE,
OAuthScopeEnum::WRITE_SCOPE
]
)
)
->build();
client := sdk.NewClient(
sdk.CreateConfiguration(
sdk.WithAuthorizationCodeAuthCredentials(
sdk.NewAuthorizationCodeAuthCredentials(
"OAuthClientId",
"OAuthClientSecret",
"OAuthRedirectUri",
).
WithOAuthScopes([]models.OAuthScopeEnum{
models.OAuthScopeEnum_READSCOPE,
models.OAuthScopeEnum_WRITESCOPE,
}),
),
),
)
Your application must obtain user authorization before it can execute an endpoint call. This authorization includes the following steps:
2. Obtain user consent
- .NET
- Java
- Python
- Ruby
- TypeScript
- PHP
- Go
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"
}
);
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 = client.getAuthorizationCodeAuth().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 state = "random_state_string";
Map<String, String> additionalParams = new HashMap<>();
additionalParams.put("prompt", "consent");
String authUrl = client.getAuthorizationCodeAuth().buildAuthorizationUrl(state, additionalParams);
To obtain user's consent, you must redirect the user to the authorization page. The get_authorization_url()
method creates the URL to the authorization page. You must have initialized the client with scopes for which you need permission to access.
auth_url = client.http_acg.get_authorization_url()
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.
auth_url = client.http_acg.get_authorization_url(
state="random_state_string", additional_params={"prompt": "consent"}
)
To obtain user's consent, you must redirect the user to the authorization page. The get_authorization_url
method creates the URL to the authorization page. You must have initialized the client with scopes for which you need permission to access.
auth_url = client.http_acg.get_authorization_url
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.
auth_url = client.http_acg.get_authorization_url(
state: 'random_state_string',
additional_params: {
prompt: 'consent'
}
)
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.
const authUrl = client.authorizationCodeAuthManager?.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.
const authUrl = client.authorizationCodeAuthManager?.buildAuthorizationUrl(
'random_state_string',
{ prompt: 'consent' }
);
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.
$authUrl = $client->getAuthorizationCodeAuth()->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.
$authUrl = $client->getAuthorizationCodeAuth()->buildAuthorizationUrl(
'random_state_string',
['prompt' => 'consent']
);
To obtain user's consent, you must redirect the user to the authorization page. The BuildAuthorizationURL()
function creates the URL to the authorization page. You must have initialized the client with scopes for which you need permission to access.
state := "random_state_string"
url := client.AuthorizationCodeAuthManager().BuildAuthorizationURL(&state)
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.
- .NET
- Java
- Python
- Ruby
- TypeScript
- PHP
- Go
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
}
String authorizationCode = getAuthCodeFromRedirectUri()
try {
OAuthToken token = client.getAuthorizationCodeAuth().fetchToken(authorizationCode);
// re-instantiate the client with oauth token
client = client.newBuilder()
.authorizationCodeAuth(client.getAuthorizationCodeAuthModel().toBuilder()
.oAuthToken(token)
.build())
.build();
} catch (Throwable e) {
// TODO Handle exception
}
auth_code = get_auth_code_from_redirect_uri()
try:
token: OAuthToken = client.http_acg.fetch_token(auth_code)
# re-initialize the client with OAuth token
client = SdkClient(
config=client.config.clone_with(
resource_owner_auth_credentials=(
client.config.resource_owner_auth_credentials.clone_with(
o_auth_token=token
)
)
)
)
except OAuthProviderException as ex:
# handle exception
pass
except APIException as ex:
# handle exception
pass
auth_code = get_auth_code_from_redirect_uri
begin
# re-initialize the client with OAuth token
client = Client.new(config: client.config.clone_with(
authorization_code_auth_credentials: client.config.authorization_code_auth_credentials.clone_with(
o_auth_token: client.http_acg.fetch_token(auth_code)
)
))
rescue OAuthProviderException, APIException => ex
puts "#{ex.class} occurred: #{ex.message}"
end
const authorizationCode = getAuthCodeFromRedirectUri();
try {
const token = await client.authorizationCodeAuthManager?.fetchToken(authorizationCode);
if (token) {
client = client.withConfiguration({
authorizationCodeAuthCredentials: {
oAuthClientId: 'OAuthClientId',
oAuthClientSecret: 'OAuthClientSecret',
oAuthRedirectUri: 'OAuthRedirectUri',
oAuthScopes: [
OAuthScopeEnum.ReadScope,
OAuthScopeEnum.WriteScope
],
oAuthToken: token
}
});
}
} catch(error) {
// handle ApiError or OAuthProviderError if needed
}
try {
$authorizationCode = self::getAuthCodeFromRedirectUri();
$token = $client->getAuthorizationCodeAuth()->fetchToken($authorizationCode);
// re-build the client with oauth token
$client = $client
->toBuilder()
->authorizationCodeAuthCredentials(
$client->getAuthorizationCodeAuthCredentialsBuilder()->oAuthToken($token)
)
->build();
} catch (ApiException $e) {
// handle exception
}
authCode := getAuthCodeFromRedirectUri()
oAuthToken, err := client.AuthorizationCodeAuthManager().FetchToken(ctx, authCode)
if err != nil {
log.Fatalln(err)
} else {
// Printing the token
fmt.Println(oAuthToken)
}
// Creating a new client with the token
client = client.CloneWithConfiguration(
sdk.WithAuthorizationCodeAuthCredentials(
client.Configuration().AuthorizationCodeAuthCredentials().
WithOAuthToken(oAuthToken),
),
)
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.
- .NET
- Java
- Python
- Ruby
- TypeScript
- PHP
- Go
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();
SdkClient client = new SdkClient.Builder()
.clientCredentialsAuth(new ClientCredentialsAuthModel.Builder(
"OAuthClientId",
"OAuthClientSecret"
)
.oAuthTokenProvider((lastOAuthToken, credentialsManager) -> {
// Add the callback handler to provide a new OAuth token
// It will be triggered whenever the lastOAuthToken is undefined or expired
OAuthToken oAuthToken = loadTokenFromDatabase();
if (oAuthToken != null && !credentialsManager.isTokenExpired(oAuthToken)) {
return oAuthToken;
}
return credentialsManager.fetchToken();
})
.oAuthOnTokenUpdate(oAuthToken -> {
// Add the callback handler to perform operations like save to DB or file etc.
// It will be triggered whenever the token gets updated
saveTokenToDatabase(oAuthToken);
})
.build())
.build();
from sdk.http.auth.o_auth_2 import ClientCredentialsAuthCredentials, OAuth2
from sdk.models.o_auth_token import OAuthToken
from sdk.sdk_client import SdkClient
def o_auth_token_provider(last_oauth_token: OAuthToken, auth_manager: OAuth2):
# Add the callback handler to provide a new OAuth token
# It will be triggered whenever the last provided o_auth_token is null or expired
o_auth_token = load_token_from_database()
if o_auth_token is None:
o_auth_token = auth_manager.fetch_token()
return o_auth_token
def o_auth_on_token_update(o_auth_token: OAuthToken):
# Add the callback handler to perform operations like save to DB or file etc.
# It will be triggered whenever the token gets updated
save_token_to_database(o_auth_token)
client = SdkClient(
client_credentials_auth_credentials=ClientCredentialsAuthCredentials(
o_auth_client_id='OAuthClientId',
o_auth_client_secret='OAuthClientSecret',
o_auth_on_token_update=o_auth_on_token_update,
o_auth_token_provider=o_auth_token_provider
)
)
client = Client.new(
client_credentials_auth_credentials: ClientCredentialsAuthCredentials.new(
o_auth_client_id: 'OAuthClientId',
o_auth_client_secret: 'OAuthClientSecret',
o_auth_token_provider: -> (last_oauth_token, auth_manager){
# Add the callback handler to provide a new OAuth token
# It will be triggered whenever the last provided o_auth_token is null or expired
o_auth_token = load_token_from_database
o_auth_token = auth_manager.fetch_token if o_auth_token.nil?
o_auth_token
},
o_auth_on_token_update: -> (o_auth_token){
# Add the callback handler to perform operations like save to DB or file etc.
# It will be triggered whenever the token gets updated
save_token_to_database(o_auth_token)
}
),
)
const client = new Client({
clientCredentialsAuthCredentials: {
oAuthClientId: 'OAuthClientId',
oAuthClientSecret: 'OAuthClientSecret',
oAuthTokenProvider: (lastOAuthToken: OAuthToken | undefined, authManager: ClientCredentialsAuthManager) => {
// Add the callback handler to provide a new OAuth token
// It will be triggered whenever the lastOAuthToken is undefined or expired
return loadTokenFromDatabase() ?? authManager.fetchToken();
},
oAuthOnTokenUpdate: (token: OAuthToken) => {
// Add the callback handler to perform operations like save to DB or file etc.
// It will be triggered whenever the token gets updated
saveTokenToDatabase(token);
}
}
});
$client = SdkClientBuilder::init()
->clientCredentialsAuthCredentials(
ClientCredentialsAuthCredentialsBuilder::init(
'OAuthClientId',
'OAuthClientSecret'
)
)
->oAuthTokenProvider(
function (?OAuthToken $lastOAuthToken, ClientCredentialsAuthManager $authManager): OAuthToken {
// Add the callback handler to provide a new OAuth token.
// It will be triggered whenever the lastOAuthToken is null or expired.
return $this->loadTokenFromDatabase() ?? $authManager->fetchToken();
}
)
->oAuthOnTokenUpdate(
function (OAuthToken $oAuthToken): void {
// Add the callback handler to perform operations like save to DB or file etc.
// It will be triggered whenever the token gets updated.
$this->saveTokenToDatabase($oAuthToken);
}
)
->build();
import (
"sdk"
"sdk/models"
)
// ...
client := sdk.NewClient(
sdk.CreateConfiguration(
sdk.WithClientCredentialsAuthCredentials(
sdk.NewClientCredentialsAuthCredentials(
"OAuthClientId",
"OAuthClientSecret",
).
WithOAuthTokenProvider(func(lastOAuthToken models.OAuthToken, authManager sdk.ClientCredentialsAuthManager) models.OAuthToken {
// Add the callback function handler to provide a new OAuth token
// It will be triggered whenever the lastOAuthToken is undefined or expired
oAuthToken, err := loadTokenFromDatabase()
if err != nil {
if token, err := authManager.FetchToken(context.TODO()); err == nil {
return token
}
}
return oAuthToken
}).
WithOAuthOnTokenUpdate(func(oAuthToken models.OAuthToken) {
// Add the callback handler to perform operations like save to DB or file etc.
// It will be triggered whenever the token gets updated
saveTokenToDatabase(oAuthToken)
}),
),
),
)
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
- .NET
- Java
- Python
- Ruby
- TypeScript
- PHP
- Go
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
}
After initializing the client, get the auth manager for a particular auth scheme. In this example, use the .getResourceOwnerAuth()
method to get it. 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.
try {
OAuthToken token = client.getResourceOwnerAuth().fetchToken();
// re-instantiate the client with oauth token
client = client.newBuilder()
.resourceOwnerAuth(client.getResourceOwnerAuthModel().toBuilder()
.oAuthToken(token)
.build())
.build();
} catch (Throwable e) {
// TODO Handle exception
}
After initializing the client, get the auth manager for a particular auth scheme. In this example, use the http_ropcg
attribute to get it. The fetch_token()
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.
from sdk.exceptions.o_auth_provider_exception import OAuthProviderException
from sdk.exceptions.api_exception import APIException
from sdk.http.auth.o_auth_2 import OAuth2
from sdk.sdk_client import SdkClient
from sdk.models.o_auth_token import OAuthToken
# client initialization here...
try:
auth_manager: OAuth2 = client.http_ropcg
token: OAuthToken = auth_manager.fetch_token()
# re-initialize the client with OAuth token
client = SdkClient(
config=client.config.clone_with(
resource_owner_auth_credentials=(
client.config.resource_owner_auth_credentials.clone_with(
o_auth_token=token
)
)
)
)
except OAuthProviderException as ex:
# handle exception
pass
except APIException as ex:
# handle exception
pass
After initializing the client, get the auth manager for a particular auth scheme. In this example, use the http_ropcg
attribute to get it. The fetch_token
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.
begin
# re-initialize the client with OAuth token
client = Client.new(
config: client.config.clone_with(
resource_owner_auth_credentials: client.config.resource_owner_auth_credentials.clone_with(
o_auth_token: client.http_ropcg.fetch_token
)
)
)
rescue OAuthProviderException, APIException => ex
puts "#{ex.class} occurred: #{ex.message}"
end
After initializing the client, get the auth manager for a particular auth scheme. In this example, use the resourceOwnerAuthManager
property to get it. 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.
try {
const token = await client.resourceOwnerAuthManager?.fetchToken();
if (token) {
client = client.withConfiguration({
resourceOwnerAuthCredentials: {
oAuthClientId: 'OAuthClientId',
oAuthClientSecret: 'OAuthClientSecret',
oAuthUsername: 'OAuthUsername',
oAuthPassword: 'OAuthPassword',
oAuthToken: token
}
});
}
} catch (error) {
console.log("Fetch token error");
// handle ApiError or OAuthProviderError if needed
}
After initializing the client, get the auth manager for a particular auth scheme. In this example, use the getResourceOwnerAuth()
method to get it. 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.
try {
$token = $client->getResourceOwnerAuth()->fetchToken();
// re-build the client with oauth token
$client = $client
->toBuilder()
->resourceOwnerAuthCredentials($client->getResourceOwnerAuthCredentialsBuilder()->oAuthToken($token))
->build();
} catch (ApiException $e) {
// handle exception
}
After initializing the client, get the auth manager for a particular auth scheme. In this example, use the ResourceOwnerAuthManager()
function to get it. The FetchToken(ctx)
function 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.
oAuthToken, err := client.ResourceOwnerAuthManager().FetchToken(ctx)
if err != nil {
log.Fatalln(err)
} else {
// Printing the token
fmt.Println(oAuthToken)
}
// Creating a new client with the token
client = client.CloneWithConfiguration(
sdk.WithResourceOwnerAuthCredentials(
client.Configuration().ResourceOwnerAuthCredentials().
WithOAuthToken(oAuthToken),
),
)
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.
- .NET
- Java
- Python
- Ruby
- TypeScript
- PHP
- Go
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.
if (client.getResourceOwnerAuth().isTokenExpired()) {
try {
OAuthToken token = client.getResourceOwnerAuth().refreshToken();
// re-instantiate the client with oauth token
client = client.newBuilder()
.resourceOwnerAuth(client.getResourceOwnerAuthModel().toBuilder()
.oAuthToken(token)
.build())
.build();
} catch (Throwable e) {
// TODO Handle exception
}
}
If a token expires, an exception will be thrown before the next endpoint call requiring authentication.
if client.http_ropcg.is_token_expired():
try:
token: OAuthToken = client.http_ropcg.refresh_token()
# re-initialize the client with OAuth token
client = SdkClient(
config=client.config.clone_with(
resource_owner_auth_credentials=(
client.config.resource_owner_auth_credentials.clone_with(
o_auth_token=token
)
)
)
)
except OAuthProviderException as ex:
print(ex)
except APIException as ex:
# handle exception
pass
If a token expires, an exception will be thrown before the next endpoint call requiring authentication.
if client.http_ropcg.token_expired?(client.config.o_auth_token)
begin
# re-initialize the client with OAuth token
client = Client.new(config: client.config.clone_with(
resource_owner_auth_credentials: client.config.resource_owner_auth_credentials.clone_with(
o_auth_token: client.http_ropcg.refresh_token
)
))
rescue OAuthProviderException, APIException => ex
puts "#{ex.class} occurred: #{ex.message}"
end
end
try {
const token = await client.resourceOwnerAuthManager?.refreshToken();
if (token) {
client = client.withConfiguration({
resourceOwnerAuthCredentials: {
oAuthClientId: 'OAuthClientId',
oAuthClientSecret: 'OAuthClientSecret',
oAuthUsername: 'OAuthUsername',
oAuthPassword: 'OAuthPassword',
oAuthToken: token
}
});
}
} catch (error) {
console.log("Fetch token error");
// handle ApiError or OAuthProviderError if needed
}
if ($client->getResourceOwnerAuth()->isTokenExpired()) {
try {
$token = $client->getResourceOwnerAuth()->refreshToken();
// re-build the client with oauth token
$client = $client
->toBuilder()
->resourceOwnerAuthCredentials($client->getResourceOwnerAuthCredentialsBuilder()->oAuthToken($token))
->build();
} catch (ApiException $e) {
// handle exception
}
}
if client.ResourceOwnerAuthManager().OAuthTokenIsExpired() {
oAuthToken, err := client.ResourceOwnerAuthManager().RefreshToken(ctx)
if err != nil {
log.Fatalln(err)
} else {
// Printing the token
fmt.Println(oAuthToken)
}
// Creating a new client with the token
client = client.CloneWithConfiguration(
sdk.WithResourceOwnerAuthCredentials(
client.Configuration().ResourceOwnerAuthCredentials().
WithOAuthToken(oAuthToken),
),
)
}