Skip to main content

Auto-Refresh OAuth 2.0 Tokens

APIMatic's SDKs support automated Auth-Token retrieval and refresh for APIs using OAuth 2.0 Grant Types. This feature enables the SDK to automatically fetch or refresh the auth-token before making any API call that requires it. By simply configuring OAuth 2.0 grant type credentials in the SDK client, users can eliminate the need for manual token management, ensuring smoother and more efficient API interactions.

note

This feature is currently limited to OAuth 2.0 Client Credentials Grant type.

Key Use Cases

  • Maintaining seamless API access for long-lived client applications.
  • Reducing the risk of authentication failures due to expired tokens.
  • Enhancing user experience by avoiding manual token refresh procedures.

Configure Auth Token Auto-Refreshing in Your OpenAPI Definition

To enable token auto-refreshing, ensure that your OpenAPI definition includes:

  1. A Security Scheme (e.g., OAuth2 with refresh token flow).
  2. Detailed configuration for token endpoints, including refresh token URLs and parameters.
components:
securitySchemes:
OAuth2:
type: oauth2
flows:
refreshToken:
tokenUrl: https://example.com/oauth/token
scopes:
read: Grants read access
write: Grants write access
security:
- OAuth2:
- read
- write

SDK Examples

const client = new SDKClient({
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
var token = loadTokenFromDatabase();
if (token === undefined) {
return authManager.fetchToken();
}
return token;
},
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);
}
},
});

Best Practices

  • Ensure refresh tokens are stored securely to prevent unauthorized access.
  • Validate the scope and permissions of the refreshed token.