You use the Token API to generate and renew user and application access tokens programmatically. The tokens are required Users need access tokens to invoke APIs subscribed under an application. Let's see how to generate/renew access tokens and authorize them. We support the four most common authorization grant types.
This section provides the following information: Table of Contents maxLevel 3 minLevel 3
...
You can obtain an access token by providing the resource owner's username and password as an authorization grant. It requires the base64 encoded string of the consumer-key:consumer-secret
combination. You need to meet the following prerequisites before using the Token API to generate a token.
Prerequisites
- A valid user account in the API Store.
- A valid consumer key and consumer secret pair. You can generate them by going to the API Store and clicking the Generate button on the My Subscriptions page.
...
- Combine the consumer key and consumer secret keys in the format consumer-key:consumer-secret and encode the combined string using base64 using the URL: http://base64encode.org.
Here's an example consumer key and secret combination :wU62DjlyDBnq87GlBwplfqvmAbAa:ksdSdoefDDP7wpaElfqvmjDue.
- Invoke the Token API by using a REST client such as the WSO2 REST Client or cURL, with the following parameters.
- Assuming that both the client and the API Gateway are run on the same server, the token API URL is https://localhost:8243/token
- payload -
"grant_type=password&username=<username>&password=<password>&scope=<scope>"
. Replace the<username>
and<password>
values as appropriate. <scope> is optional, you can leave it off if necessary - headers -
Authorization: Basic <base64 encoded string>, Content-Type: application/x-www-form-urlencoded
. Replace the<base64 encoded string>
as appropriate.
For example, use the following cURL command to access the Token API. It generates two tokens as an access token and a refresh token. You can use the refresh token at the time a token is renewed.
Code Block curl -k -d "grant_type=password&username=<username>&password=<password>" -H "Authorization: Basic SVpzSWk2SERiQjVlOFZLZFpBblVpX2ZaM2Y4YTpHbTBiSjZvV1Y4ZkM1T1FMTGxDNmpzbEFDVzhh, Content-Type: application/x-www-form-urlencoded" https://localhost:8243/token
Code Block title CuRL command with Scopes curl -k -d "grant_type=password&username=<username>&password=<password>&scope<scope1> <scope2>" -H "Authorization: Basic SVpzSWk2SERiQjVlOFZLZFpBblVpX2ZaM2Y4YTpHbTBiSjZvV1Y4ZkM1T1FMTGxDNmpzbEFDVzhh, Content-Type: application/x-www-form-urlencoded" https://localhost:8243/token
Info title A note about scopes When defining an API, the API creator is able to specify a scope for its resources. The resources can only be accessed through a token that has been issued for at least the scope belonging to the API resource. For example, if a resource has been defined for a scope named 'update' and if the token had been issued for the scopes 'read' and 'update', the token will be allowed to access the resource. If the token had been issued for a scope named 'read', the request bearing the particular token will be blocked.
Generating access tokens with authorization code (authorization code grant type)
Instead of requesting authorization directly from the resource owner (resource owner's credentials), in this grant type, the client directs the resource owner to an authorization server. The authorization server works as an intermediary between the client and resource owner to issues an authorization code, authenticate the resource owner and obtain authorization. As this is a redirection-based flow, the client must be capable of interacting with the resource owner's user-agent (typically a Web browser) and receiving incoming requests (via redirection) from the authorization server.
The client initiates the flow by directing the resource owner's user-agent to the authorization endpoint (you can use the /authorize
endpoint for the authorization code grant type of OAuth2.0). It includes the client identifier, response_type, requested scope, and a redirection URI to which the authorization server sends the user-agent back after granting access. The authorization server authenticates the resource owner (via the user-agent) and establishes whether the resource owner granted or denied the client's access request. Assuming the resource owner grants access, the authorization server then redirects the user-agent back to the client using the redirection URI provided earlier. The redirection URI includes an authorization code.
The client then requests an access token from the authorization server's /token
endpoint by including the authorization code received in the previous step. When making the request, the client authenticates with the authorization server. It then includes the redirection URI used to obtain the authorization code for verification. The authorization server authenticates the client, validates the authorization code, and ensures that the redirection URI matches the URI used to redirect the client from the /authorize endpoint in the previous response. If valid, the authorization server responds back with an access token and, optionally, a refresh token.
Invoking the Token API to generate tokens
The Authorization AP'sI URL is https://localhost:8243/authorize. The HTTP request can have the following parameters:
- query component:
response_type=code&client_id=<consumer_key>&scope=PRODUCTION&redirect_uri=<application_callback_url>
- headers:
Content-Type: application/x-www-form-urlencoded
For example, the client directs the user-agent to make the following HTTP request using TLS.
Code Block |
---|
GET
/authorize?response_type=code&client_id=wU62DjlyDBnq87GlBwplfqvmAbAa&scope=PRODUCTION&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
HTTP/1.1
Host: server.example.com
Content-Type: application/x-www-form-urlencoded |
The authorization server redirects the user-agent by sending the following HTTP response:
Code Block |
---|
HTTP/1.1 302 Found
Location:
https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA |
The client makes the following HTTP request using TLS to the /token endpoint.
Code Block |
---|
POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic
SVpzSWk2SERiQjVlOFZLZFpBblVpX2ZaM2Y4YTpHbTBiSjZvV1Y4ZkM1T1FMTGxDNmpzbEFDVzhh
Content-Type:
application/x-www-form-urlencoded
grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb |
The /token endpoint responds in the same way like in password grant type.
Exchanging SAML2 bearer tokens with OAuth2 (SAML extension grant type)
SAML 2.0 is an XML-based protocol. It uses security tokens containing assertions to pass information about an end user between a SAML authority and a SAML consumer. A SAML authority is an identity provider (IDP) and a SAML consumer is a service provider (SP).
A lot of enterprise applications use SAML2 to engage a third-party identity provider to grant access to systems that are only authenticated against the enterprise application. These enterprise applications might need to consume OAuth-protected resources through APIs, after validating them against an OAuth2.0 authentication server. However, an enterprise application that already has a working SAML2.0 based SSO infrastructure between itself and the IDP prefers to use the existing trust relationship, even if the OAuth authorization server is entirely different from the IDP. The SAML2 Bearer Assertion Profile for OAuth2.0 helps leverage this existing trust relationship by presenting the SAML2.0 token to the authorization server and exchanging it to an OAuth2.0 access token.
WSO2 API Cloud acts as an authorization server and provides SAML2 Bearer Assertion Profile Support with the OAuth 2.0 feature. An enterprise application can exchange the SAML2.0 bearer token that it retrieves when authenticating against an IDP (e.g., WSO2 Identity Server) with an OAuth2.0 access token from an OAuth authorization server (e.g., WSO2 API Cloud). It can then use the OAuth2 token in API invocations.
The diagram below depicts this scenario:
The scenarios of the above diagram are explained below:
Scenario [1]: User initiates login call to an enterprise application .
Scenario [2]:
- As the application is a SAML SP, it redirects the user to the SAML2.0 IDP to log in.
- The user provides credentials at the IDP and is redirected back to the SP with a SAML2.0 token signed by the IDP.
- The SP verifies the token and logs the user to the application.
- The SAML 2.0 token is stored in the user's session by the SP.
Scenario [3]:
- The enterprise application (SP) wants to access an OAuth2 protected API resource through the API Cloud.
- The application makes a request to the API Cloud to exchange the SAML2 bearer token for an OAuth2.0 access token.
- The API Cloud validates the assertion and returns the access token.
Scenario [4]: User does API invocations through the API Cloud by setting it as an Authorization header with the returned OAuth2 access token.
Let's see how to configure the token exchange.
Prerequisites
- A signed SAML2 token (encoded assertion value), which you retrieve when authenticating against a SAML2 IDP. With the authentication request, you must pass attributes such as SAML2 issuer name, token endpoint and the restricted audience. To specify those attributes,
Log in to the management console (https://localhost:9443/carbon) using admin/admin credentials and select Add under Identity Providers menu in the Main menu.
- Provide the following values in the page that opens:
- Under Basic Information
- Identity Provider Name: Enter a unique name for IDP
- Identity Provider Public Certificate: Upload Identity Provider public certificate
- Alias: Give the name of the alias if the Identity Provider identifies this token endpoint by an alias
Under Federated Authenticators -> SAML2 Web SSO Configuration
Identity Provider Entity Id: The SAML2 issuer name specified when generating assertion token, which contains the unique identifier of the IDP
- Service Provider Entity Id:
- SSO URL: Enter the IDP's SAML2 Web SSO URL value
- Under Basic Information
- A valid user account in the API Store.
- A valid consumer key and consumer secret. Initially, these keys must be generated through the management console by clicking the Generate link on My Subscriptions page.
...
Follow the steps below to invoke Token API to generate access tokens from SAML2 assertions.
...
- The Token API URL is https://localhost:8243/token. It can take the following parameters:
- payload:
"grant_type=urn:ietf:params:oauth:grant-type:saml2-bearer&assertion=<SAML2_Encoded_Assertion_Token>
&scope=PRODUCTION"
. Replace the<SAML2_Encoded_Assertion_Token>
value as appropriate. - headers:
Authorization :Basic <base64 encoded string>, Content-Type: application/x-www-form-urlencoded
. Replace the<base64 encoded string>
as appropriate.
- payload:
For example, use the following cURL command used to access the Token API generates an access token and a refresh token. You can use the refresh token at the time a token is renewed.
Code Block |
---|
curl -k -d "grant_type=urn:ietf:params:oauth:grant-type:saml2-bearer&assertion=<SAML2_Encoded Assertion>&scope=PRODUCTION" -H "Authorization: Basic SVpzSWk2SERiQjVlOFZLZFpBblVpX2ZaM2Y4YTpHbTBiSjZvV1Y4ZkM1T1FMTGxDNmpzbEFDVzhh, Content-Type: application/x-www-form-urlencoded" https://localhost:8243/token |
...
Access tokens are passed in the HTTP header when invoking APIs. The API Cloud provides a Token API that you can use to generate and renew user and application access tokens. The response of the Token API is a JSON message. You extract the token from the JSON and pass it with an HTTP Authorization header to access the API.
The following topic explain how to generate/renew access tokens and authorize them. WSO2 API Cloud supports the four most common authorization grant types and you can also define additional types.
Child pages (Children Display)
Also see the following: Table of Contents
Renewing access tokens
Anchor | ||||
---|---|---|---|---|
|
After an access token is generated, sometimes you might have to refresh or renew the old token due to expiration or security concerns. This can be done by issuing a REST call to the Token API through a REST client like cURL, with the following parameters.
- The Token API URL is
https://
localhostapi.cloud.wso2.com:8243/token
. It can take the following parameters: - payload : -
"grant_type=refresh_token&refresh_token=<retoken>&scope=PRODUCTION"
. Replace the<retoken>
value value with the refresh token generated in the the previous section. - headers : -
Authorization :Basic <base64 encoded string>, Content-Type: application/x-www-form-urlencoded
. Replace Replace<base64 encoded string>
as as appropriate.
For example, the following cURL command can be used to access the Token API.
Code Block |
---|
curl -k -d "grant_type=refresh_token&refresh_token=<retoken>&scope=PRODUCTION" -H "Authorization: Basic SVpzSWk2SERiQjVlOFZLZFpBblVpX2ZaM2Y4YTpHbTBiSjZvV1Y4ZkM1T1FMTGxDNmpzbEFDVzhh, Content-Type: application/x-www-form-urlencoded" https://localhost:8243/token |
...
After issuing an access token, a user or an admin can revoke it in case of theft or a security violation. You can do this by calling the Revoke API using a client like cURL.
...
REST Client. The Revoke API's endpoint URL is
...
...
api.cloud.wso2.com:8243/revoke
. The parameters required to invoke this API are as follows:
- The token to be revoked
- Consumer key and consumer secret key. Must be encoded using Base64 algorithm
For example, curl -k -d "token=<ACCESS_TOKEN_TO_BE_REVOKED>" -H "Authorization: Basic Base64Encoded(Consumer Consumer key:consumer secret secret)"http https://localhost:8280/revokeapi.cloud.wso2.com:8243/revoke.
Tip |
---|
When the API Gateway cache is enabled (it is enabled by default), even after revoking a token, it might still be available in the cache to consumers until the cache expires in approximately 15 minutes. |