Java SDK for OAuth 2.0 Services


The open-source Java SDKs for cidaas uses the Nimbus library to offer built-in support for client-side OAuth 2.0 services.

You can use this open-source Java SDK for cidaas integration on your web apps.

During authentication, the user is redirected to the cidaas web portal on a browser where they can log in and authorize data access by the third-party application before being redirected to the Application’s redirect_url.

This last step requires the application to be running on a web server accessible to the user.

You can complete an OAuth 2.0 flow with these steps.

  1. Configure the opensource Java SDK for cidaas.
  2. Redirect the user to the cidaas portal for Authentication.
  3. The user grants the application access.
  4. Exchange the authorization code for an access token.

The following block diagram (illustrating an e-signature example) depicts the conventional OAuth 2.0 flow for a customer app’s cidaas integration.

At the end of this flow, the customer’s application has an Access Token that it uses to make API calls on the user’s behalf.


Note: The action token acquired through OAuth 2.0 is inherently tied to the user who authorized the application. Any API call made with this token seems to come from this application, and the user needs to have access to any resource the application tries to access with this token.

Nimbus SDK

This open-source Java library is your starting point for developing OAuth 2.0 based applications in Java. It provides ready and simple-to-use classes for dealing with tokens and representing the protocol messages, ensuring standards compliance and interoperability.

The OAuth 2.0 standard permits application-specific profiles and extensions, and this library also caters to that, with suitable interfaces and base classes where required.

Supported OAuth 2.0 Endpoints

  • Authentication (OAuth 2.0 Authorization) Endpoint.
  • Token Endpoint.
  • Token Introspection Endpoint.
  • Token Revocation Endpoint.

Supported Tokens

  • Bearer Tokens- A Bearer token is a security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

  • Typeless Access Token - This represents an object encapsulating the security identity of a process or thread and cannot be serialised and is intended to represent parsed access tokens for which type cannot be inferred.
  • Refresh tokens- These are credentials used to obtain access tokens. Refresh tokens are issued to the client by the Authorization Server and are used to obtain a new access token when the current access token becomes invalid or expires, or to obtain additional access tokens with identical or narrower scope.
  • ID Tokens- These tokens are used in token-based authentication to cache user profile information and provide it to a client application, thereby providing better performance.

Features

  1. Support for plain signed and encrypted request objects and JSON Web Tokens (JWT) via the Nimbus JOSE+JWT library.
  2. Extensible ID token and UserInfo claim set to allow passing and processing of additional custom claims.
  3. Java Servlet integration support.
  4. Standards compliance, robust and extensible
  5. Open-source (Apache 2.0 license).

This SDK version implements the following standards.

  1. The OAuth 2.0 Authorization Framework.
  2. The OAuth 2.0 Authorization Framework: Bearer Token Usage.
  3. OAuth 2.0 Token Introspection.
  4. OAuth 2.0 Token Revocation.
  5. OAuth 2.0 Authorization Server Metadata.
  6. Assertion Framework for OAuth 2.0 Client Authentication and Authorization Grants.
  7. JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants.
  8. SAML 2.0 Profile for OAuth 2.0 Client Authentication and Authorization Grants.
  9. Authentication Method Reference values.
  10. OAuth 2.0 Authorization Server Metadata.

OAuth 2.0 Authorization Framework

This Framework is a protocol used on cidaas to allow a user to grant a third-party website or application access to the user's protected resources, using passwordless and other authentication methods.

OAuth introduces an authorization layer and separates the role of cidaas from that of the resource owner.

In this OAuth implementation, cidaas requests access to resources controlled by the resource owner and hosted by the resource server and are issued a different set of credentials than those of the resource owner.

Instead of using the resource owner's credentials to access protected resources, cidaas obtains an access token-- a string denoting a specific scope, lifetime, and other access attributes.

Access tokens are issued to cidaas by an Authorization Server with the approval of the resource owner. Then, cidaas uses the access token to access the protected resources hosted by the resource server.

OAuth generates access tokens for API authorization scenarios in JSON web token (JWT) format. The permissions represented by the access token, in OAuth terms, are known as scopes.

When an application authenticates with Auth0, it specifies the scopes it wants. If the user authorizes those scopes, then the access token will represent these authorized scopes.

Roles

An OAuth 2.0 flow has the following roles:

  1. Resource Owner: This represents an Entity that can grant access to a protected resource. Typically, the end-user.
  2. Resource Server: This is the Server hosting the protected resources and the API you want to access.
  3. Client: This is the Application requesting access to a protected resource on behalf of the Resource Owner, in this case, cidaas.
  4. Authorization Server: This is the Server that authenticates the Resource Owner and issues access tokens after getting proper authorization. In this case, Auth0.

Grant Types

OAuth 2.0 defines four flows to get an access token. These flows are called grant types. Deciding which one is suited for your case depends mainly on your application type.

  1. Authorization Code Flow: This flow is used by Web Apps executing on a server and mobile apps.
  2. Implicit Flow with Form Post: This is used by JavaScript-centric apps (Single-Page Applications) executing on the user's browser.
  3. Resource Owner Password Flow: This is used by highly trusted apps.
  4. Client Credentials Flow: This is used for machine-to-machine communication.

Parameter List

Parameter Description
CLIENT_ID The client ID or API key for the application.
CLIENT_SECRET The client secret or API secret for the application.
REDIRECT_URI The redirect URL for your application that a user will be sent to after they have authorized the application. This can be configured in the Developer Console.

OAuth 2.0 Authorization Steps

Configure SDK

The first step is to make sure your environment has been prepared by configuring the SDK of your choice using the following Java code.


import com.cidaas.sdk.cidaasAPIConnection;
String authorizationUrl = "https://account.cidaas.com/api/oauth2/authorize?client_id=[CLIENT_ID]&response_type=code";

Redirect User

Next, you need to redirect the user to the authorization URL using the following code. Most of the SDKs support a way to get the authorization URL for an SDK client.


String authorizationUrl = "https://account.cidaas.com/api/oauth2/authorize?client_id=[CLIENT_ID]&response_type=code";
// response.redirect(authorizationUrl);

The way in which a user is redirected to a URL depends on the application framework used.

The redirect URL can also be created manually as follows.

https://account.cidaas.com/api/oauth2/authorize?client_id=[CLIENT_ID]&redirect_uri=[REDIRECT_URI]&response_type=code

Additional query parameters can be passed along when redirecting the user to limit down the scope, or pass along some extra state.

Authorization Request to the Authorization Server

The Authorization request contains three parameters clientId, callbackUrl/redirectUrl, and scopes as you can see below.


Authorisation authorisation = new Authorisation();
authorisation.AuthorisationRequest(clientId, callbackUrl, scopes);

Once this request is passed, the user will be redirected to the Authorization Server URL (in this case cidaas login page) where the user will be authorized and authenticated using their credentials.

cidaas has multiple authentication options for users like email/username and password credentials, passwordless authentication using SMS or email OTP, social pages login, and more.

After successful authorization, the user will be redirected to a callback URL from which a code can be obtained. Using this code, a client or user can request for the access token obtaining which the client can access the resources mentioned in scopes.

Exchange Code

The user is redirected to the customer application's redirect URL with a query parameter containing a short-lived authorization code.

Example: https://www.cidaas.com/path?code=1234567

This code is not an Access Token and is only valid for a few seconds. The SDKs can be used to exchange the code for an actual Access Token using the following code.


cidaasAPIConnection client = new cidaasAPIConnection(
  "[CLIENT_ID]",
  "[CLIENT_SECRET]",
  "[CODE]"
);

At the end of this flow, the application has an Access Token that can be used to make API calls on behalf of this user.

Authorization Resources

Access Token

An Access Token is an opaque string (or a JWT in an Auth0 2.0 implementation) that denotes who has authorized which permissions (scopes) to which application.

It is meant to be exchanged with an access token at the /oauth/token Endpoint.

To inform the Authorization Server which grant type to use, the response_type request parameter is used as follows:

  • For the Authorization Code grant, use response_type=code to include the authorization code.
  • For the Implicit grant, use response_type=token to include an access token.
This token is used to make authenticated API calls and contains the following parameters.
Parameter Type Mandate Description
ACCESS_TOKEN string/token Required The requested access token.
EXPIRES_IN integer/int64 Required The time in seconds in seconds by which this token will expire.
ISSUED_TOKEN_TYPE string/urn Required Value is always urn:ietf:params:oauth:token-type:access_token
REFRESH_TOKEN string/token Required This is the refresh token for the access token, which can be used to request a new access token when the current one expires.
RESTRICTED_TO object array Optional This refers to the permissions that this access token provides along with the list of resources (files, folders, etc.), and the scopes permitted for each of those resources.
[restricted_to].object File (Mini) object Optional The file for which the file can be accessed.
[restricted_to].scope String Optional The file scopes for the file access. Value is one of the following. annotation_edit, annotation_view_all, annotation_view_self, base_explorer, base_picker, base_preview, base_upload, item_delete, item_download, item_preview, item_rename, item_share
TOKEN_TYPE String Optional Value is always bearer.

Authorization Endpoint

The /authorize Endpoint is used to interact with the resource owner and get the authorization to access the protected resource.

To better understand this, imagine that you want to log in to a service using your cidaas account.

First, the service redirects you to cidaas to authenticate (if you are not already logged in) and then you will get a consent screen, where you will be asked to authorize the service to access some of your data (protected resources); for example, your email address and your list of contacts.

The request parameters of the /authorize Endpoint are:

Parameter Mandate Description
Response_type Required Tells the Authorization Server which grant to execute.
Response_mode Optional This depicts how the result of the Authorization Request is formatted. The values include:
  • query: for Authorization Code grant. 302 Found: triggers redirect.
  • fragment: for Implicit grant. 302 Found: triggers redirect. The response parameters are embedded in the fragment component (the part after #) of the redirect_uri in the Location header.
  • form_post: 200 OK with response parameters embedded in an HTML form as hidden parameters.
  • web_message:For Silent Authentication. Uses HTML5 web messaging. It uses HTML5 Web Messaging instead of the redirect for the authorization response from the /authorization Endpoint.
client_id Required The ID of the application that asks for authorization.
redirect_uri Required Holds a URL. A successful response from this Endpoint results in a redirect to this URL.
scope Required A space-delimited list of permissions that the application requires.
state Required An opaque value, used for security purposes. If this request parameter is set in the request, then it is returned to the application as part of the redirect_uri.

Authorize User API Endpoint

The following API Endpoint is used to authorize a user by sending them through the cidaas website and request their permission to act on their behalf.

GET https://account.cidaas.com/api/oauth2/authorize/

This is the first step in user authentication using OAuth 2.0.

To request a user's authorization to use the cidaas APIs on their behalf, you will need to redirect the user to the URL with the following request format.

Content-Type application/json

The Query Parameters used at this Endpoint include:

Parameter Type Mandate Description
client_id String Required This is the client ID of the application that is requesting to authenticate the user. To get the Client ID for your application, log in to your developer console and navigate to the OAuth 2.0 Parameters section under the configuration page. Here, you will find the item labeled client_id. The text of that item is your application's Client ID.
redirect_uri String/url Optional The URL to which cidaas redirects the browser after the user has granted or denied the application permission. This URL must match the redirect URL in the configuration of your application. It must be a valid HTTPS URL and it needs to handle the redirection to complete the next step in the OAuth 2.0 flow.
resource_type String/token Required Value of this parameter is always Code.
scope String Optional A comma-separated list of application scopes you'd like to authenticate the user for. The default scope is all the scopes configured for the application in its configuration page.
state String Optional A custom string provided by the user which will be passed to the redirect URL when authentication is complete. This parameter can be used to identify a user on redirect, as well as provide protection against session attacks.

Response to the above Request

Value: 200 (Text/HTML)

Description: Does not return any data, but rather should be used in the browser.

Value: default (Text/HTML)

Description: Does not return any data, but rather should be used in the browser

OAuth 2.0 Authorization Request

The client obtains the end-user's Authorization (consent) to access some protected resource like a web API at the /authorize Endpoint on the user's behalf.

Here is the detailed process.

  1. The client sends the end-user's browser to the Authorization Endpoint of the OAuth 2.0 server. The Authorization Request is encoded in the query string of the URI.

  2. At the Authorization Endpoint, the end-user is typically authenticated and then presented with a consent form or screen. There is no particular authentication or consent method. The server may, for instance, check the browser for a valid session cookie, and when it’s unavailable, the server prompts the user for a password for authentication. The Authorization may be obtained without any user interaction, e.g. by applying a policy. Regardless of the interaction, the server should arrive at a decision whether the requesting client has access permission or not.

  3. The server sends the end-user's browser back to the client. The response is encoded in the query or fragment string of the URI. Depending on which response_type the client has requested, the server will return the following success responses:

    • An Authorization code which the client can later exchange for an access token at the Token Endpoint of the server. This response type requires two steps to obtain a token and is the preferred one for web applications (code flow or grant).

    • The Access Token directly. This response type is intended for browser-based JavaScript apps and is less secure (implicit flow or grant).

Prerequisites

  1. The client must be registered with the server and have a valid client ID. The client registration may also lock down some of the request parameters, such as the permitted response type, callback URI(s) and available scope values.

  2. The client must be able to maintain a secure state between the request and the callback response. The state parameter is intended for that purpose, typically represented by a long random number which is stored in the user session with the client.

Authorization Request - Sample code

import com.nimbusds.oauth2.sdk.*;
import com.nimbusds.oauth2.sdk.id.*;

// The Authorization endpoint of the server
URI authzEndpoint = new URI("https://cidaas.com/authz");

// The client identifier provisioned by the server
ClientID clientID = new ClientID("123");

// The requested scope values for the token
Scope scope = new Scope("read", "write");

// The client callback URI, typically pre-registered with the server
URI callback = new URI("https://client.com/callback");

// Generate random state string for pairing the response to the request
State state = new State();

// Build the request
AuthorizationRequest request = new AuthorizationRequest.Builder(
    new ResponseType(ResponseType.Value.CODE), clientID)
    .scope(scope)
    .state(state)
    .redirectionURI(callback)
    .endpointURI(authzEndpoint)
    .build();

// Use this URI to send the end-user's browser to the server
URI requestURI = request.toURI();

Client Callback Endpoint - Sample Codes

Authorization Response

import com.nimbusds.oauth2.sdk.*;
import com.nimbusds.oauth2.sdk.id.*;

AuthorizationResponse response = AuthorizationResponse.parse(new URI("..."));

if (! state.equals(response.getState()) {
    // Unexpected or tampered response, stop!!!
    return;
}
if (! response.indicatesSuccess()) {
    // The request was denied or some error occurred
    AuthorizationErrorResponse errorResponse = response.toErrorResponse();
    System.out.println(errorResponse.getErrorObject());
    return;
}

AuthorizationSuccessResponse successResponse = response.toSuccessResponse();

AuthorizationCode code = successResponse.getAuthorizationCode();

OAuth 2.0 Authorization Request - implicit flow


import com.nimbusds.oauth2.sdk.*;
import com.nimbusds.oauth2.sdk.id.*;
import com.nimbusds.oauth2.sdk.token.*;

URI authzEndpoint = new URI("https://cidaas.com/authz");

ClientID clientID = new Client("123");

Scope scope = new Scope("read", "write");

URI callback = new URI("https://client.com/callback");

State state = new State();

AuthorizationRequest request = new AuthorizationRequest.Builder( 
  new ResponseType(ResponseType.Value.TOKEN), clientID)
 .scope(scope)
 .state(state)
 .redirectionUR(callback)
 .endpointURI(authzEndpoint)
 .build();

URI requestURI = request.toURI();

Returning the State Parameter


import com.nimbusds.oauth2.sdk.*;
import com.nimbusds.oauth2.sdk.id.*;

// Parse the Authorization response from the callback URI

AuthorizationResponse response = AuthorizationResponse.parse(new URI("..."));

// Check the returned state parameter, must match the original

if (! state.equals(response.getState()) {
    // Unexpected or tampered response, stop!!!
    return;
}
if (! response.indicatesSuccess()) {
    // The request was denied or some error occurred
    AuthorizationErrorResponse errorResponse = response.toErrorResponse();
    System.out.println(errorResponse.getErrorObject());
    return;
}
AuthorizationSuccessResponse successResponse = response.toSuccessResponse();

// Retrieve the token, which can now be used to make requests to the

// protected resource (web API)

AccessToken token = successResponse.getAccessToken();

Get the query string from the Request URI


import com.nimbusds.oauth2.sdk.*;
import com.nimbusds.oauth2.sdk.id.*;
// Get the query string from the request URI
String query = requestURI.getQuery();
// Parse the Authorization request
AuthorizationRequest request = AuthorizationRequest.parse(query);
// Extract and validate the request parameters
// Required to look up the client in the server's database
ClientID clientID = req.getClientID();
// The client callback URL, must be registered in the server's database
URL callback = req.getRedirectionURI();
// The state, must be echoed back with the response
State state = req.getState();
// The requested scope
Scope scope = req.getScope();
// Authenticate the end-user, gather consent.
// Generate the response.
AuthorizationResponse response;
if (success) 
{
    if (request.getResponseType().equals(new ResponseType(ResponseType.Value.CODE)) {

        // Generate Authorization code and save it.
        AuthorizationCode code = new AuthorizationCode();
        response = AuthenticationSuccessResponse(callback, code, state);
    } else if (request.getResponseType().equals(new ResponseType(ResponseType.Value.TOKEN)) {
        // Generate access token
        AccessToken code = new BearerAccessToken(...);
        response = AuthenticationSuccessResponse(callback, code, state);
    }
} else if (authorizationDenied) {
    // Signal access denied
    response = new AuthorizationErrorResponse(callback,
        OAuth2Error.ACCESS_DENIED,
        request.getResponseType(),
        state);
} else {
    // Handle other errors
}
// Output the response depending on your web server framework.

OAuth 2.0 Error Format

Value: error

Type: string

Example: invalid_client

Description: This is the type of the error returned.

Value: error_description

Type: string

Example: The client credentials are not valid.

Description: This is the type of the error returned.

Token Endpoint

The client uses the Token Endpoint to obtain an access token by presenting its authorization grant or refresh token. The Token Endpoint is used with every authorization grant except for the implicit grant type (since an access token is issued directly).

The application uses the /oauth/token Endpoint to get an access token or a refresh token. All flows use it except for the Implicit Flow. Because, in that case, an access token is issued directly.

  • In the Authorization Code Flow, the application exchanges the authorization code it got from the Authorization Endpoint for an Access Token.
  • In the Client Credentials Flow and Resource Owner Password Credentials Grant Exchange, the application authenticates using a set of credentials and then gets an access token.

The Endpoint URI MAY include an application/x-www-form-urlencoded query component, which MUST be retained when adding additional query parameters. The Endpoint URI MUST NOT include a fragment component.

Since requests to the token endpoint result in the transmission of clear-text credentials (in the HTTP request and response), the Authorization Server MUST use TLS when sending requests to the Token Endpoint.

The client MUST use the HTTP POST method when making access token requests. Parameters sent without a value MUST be treated as if they were omitted from the request.

The Authorization Server MUST ignore unrecognized request parameters. Request and Response parameters MUST NOT be included more than once.

Grants used at the Token Endpoint

The core OAuth 2.0 specification defines four types of grants for use at the Token Endpoint. An Authorization Server may support one or more of these.

1. Authorization code -- this is an opaque credential obtained at the Authorization Endpoint, encapsulating the end-user's consent given to the client. The code grant is the most commonly used one, and it offers optimal security.

2. Resource owner password credentials -- the client collects the end-user's username and password and submits them to the OAuth 2.0 Server

Note: Don't use this grant unless you absolutely can't have the code or implicit grant.

The whole point of OAuth is to provide a single trusted point for users to submit their credentials, so any security pitfalls of disclosing user credentials to client apps are completely avoided.

3. Client credentials -- intended for cases when the client is acting on its own behalf (the client is the resource owner. The grant is the client's registered credentials client_id and usually a client_secret).

4. Refresh token -- opaque credential issued by the Authorization Server, allows the client to obtain a new access token when the current access token becomes invalid or expires.

The implicit grant (or flow) is the only one which doesn't require the client to interact with the Token Endpoint of the OAuth 2.0 Server. Instead, client receives the access token directly from the Authorization Endpoint.

The grant is an open concept, and since the publication of the code OAuth 2.0 spec a number of other grant types were developed. One such grant enables the exchange of SAML assertions for access tokens. Another, to handle input constrained devices.

Client Authentication

Confidential clients or other clients issued with credentials MUST authenticate with the Authorization Server when making requests to the Token Endpoint.

Client authentication is used for:

1. Enforcing the binding of refresh tokens and authorization codes to the client they were issued to. Client authentication is critical when an authorization code is transmitted to the Redirection Endpoint over an insecure channel or when the redirection URI has not been registered in full.

2. Recovering from a compromised client by disabling the client or changing its credentials, thus preventing an attacker from abusing stolen refresh tokens. Changing a single set of client credentials is significantly faster than revoking an entire set of refresh tokens.

3. Implementing the best practices in authentication management that require periodic credential rotation. Rotation of an entire set of refresh tokens can be challenging, while rotation of a single set of client credentials is significantly easier.

4. A client MAY use the client_id request parameter to identify itself when sending requests to the Token Endpoint. In the authorization_code grant_type request to the Token Endpoint, an unauthenticated client MUST send its client_id to prevent itself from inadvertently accepting a code intended for a client with a different client_id. This protects the client from substitution of the authentication code.

Request Access Token

POST https://api.cidaas.com

You can Request an Access Token using either a client-side obtained OAuth 2.0 authorization code or a server-side JWT assertion.

An Access Token is a string that enables cidaas to verify that a request belongs to an authorized session.

Typically, you need to request authentication from the Authorize Endpoint, and cidaas will send you an Authorization Code.

This code will then be sent to this Endpoint to exchange it for an Access Token. The returned Access Token can then be used to make cidaas API calls.

Request Code

Content-Type application/x-www-form-urlencoded

Request Body Parameters

Parameter Type Mandate Description
actor_token string/token Optional This is the token used to create an annotator token. This is a JWT assertion. Used in combination with urn:ietf:params:oauth:grant-type:token-exchange as the grant_type
actor_token_type string/urn Optional The value is always urn:ietf:params:oauth:token-type:id_token.
assertion string/jwt Optional Used in combination with urn:ietf:params:oauth:grant-type:jwt-bearer as the grant_type.
cidaas_subject_id string Optional Used in combination with client_credentials as the grant_type.Value is determined by cidaas_subject_type. If user then use user ID otherwise if enterprise then use enterprise ID.
cidaas_subject_type string Optional Used in combination with client_credentials as the grant_type.Value is one of enterprise user.
client_id string optional Used in combination with client_credentials as the grant_type.Value is one of enterprise or user.
client_secret string optional The client secret of the application requesting an access token. Used in combination with authorization_code, client_credentials, or urn:ietf:params:oauth:grant-type:jwt-bearer as the grant_type.
code string/token Optional The client-side authorization code passed to your application by cidaas in the browser redirect after the user has successfully granted your application permission to make API calls on their behalf. Used in combination with authorization_code as the grant_type.
grant_type string/urn optional The type of request being made, either using a client-side obtained authorization code, a refresh token, a JWT assertion, client credentials grant or another access token for the purpose of down-scoping a token. Value is either authorization_code, refresh_token, client_credentials, urn:ietf:params:oauth:grant-type:jwt-bearer, or urn:ietf:params:oauth:grant-type:token-exchange
refresh_token string/token optional This is the refresh token used to get a new access token and is used in combination with refresh_token as the grant_type.
resource string/url optional Full URL for the file that the token should be generated for.
scope string / space_delimited_list optional The space-delimited list of scopes that you want apply to the new access token. The subject_token will need to have all of these scopes or the call will error with 401 Unauthorized.
subject_token string/token optional The token to exchange for a down-scoped token. This can be a regular access token, a JWT assertion, or an app token. Used in combination with urn:ietf:params:oauth:grant-type:token-exchange as the grant_type.
subject_token_type string optional The value is always urn:ietf:params:oauth:token-type:access_token.


Response

Value:200 application/json

Description:

Returns a new Access Token that can be used to make Authenticated API calls by passing along the token in an Authorization header- Authorization: Bearer < Token >.

Value:400 application/json

Description: An Authentication Error.

Value: default application/json

Description: An Authentication Error.


Refresh Access Token

POST https://api.cidaas.com/oauth2/token/

Description: This POST request is used to refresh an Access Token using its client ID, secret, and refresh token.

Request

Content-Type application/x-www-form-urlencoded/

Request Body Parameters

Parameter Type Mandate Description
client_id string Required The client ID of the application requesting to refresh the token.
client_secret string Required The client secret of the application requesting to refresh the token.
grant_type string/urn Required The value is always refresh_token.
refresh_token string/token Required The refresh token that is used to refresh.


Response

Value: 200 application/json

Description: Returns a new Access Token that can be used to make Authenticated API calls by passing along the token in an Authorization header- Authorization: Bearer < Token >

Value:400 application/json

Description: An authentication error.


Revoke Access Token

POST https://api.box.com/oauth2/revoke/

This POST request is used to “Revoke” an active Access Token while effectively logging out a previously-authenticated user.

Request

Content-Type application/x-www-form-urlencoded

Request Body Parameters

Parameter Type Mandate Description
client_id string Optional The client ID of the application requesting to revoke the token.
client_secret string Optional The client secret of the application requesting to revoke the token.
token string Optional The access token used to revoke.


Response

Value: 200 none

Description: Returns an empty response when the token was successfully revoked.

Value: 400 application/json

Description: An Authentication Error.

Value: default application/json

Description: An Authentication Error.


OAuth 2.0 Token Request

The Token Endpoint of an OAuth 2.0 Authorization Server is where a client obtains its access token in exchange for a valid credential called a grant.

The core OAuth 2.0 spec defines four types of grants for use at the Token Endpoint. An Authorization Server may support one or more of them.

1. Authorization code -- An opaque credential obtained at the Authorization Endpoint encapsulates the client's consent given to the client. The code grant is the most commonly used one, and it offers the best security.

2. Resource owner password credentials -- The client collects the end-user's username and password and submits them to the OAuth 2.0 Server.

Note: Don't use this grant unless you absolutely can't have the code or implicit grant.

The whole point of OAuth is to provide a single trusted point for users to submit their credentials, so they can avoid the various security pitfalls of disclosing user credentials to client apps.

3. Client credentials -- Intended for cases where the client is the resource owner and the grant is the client's registered credentials (client_id and usually a client_secret).

4. Refresh token – This is an opaque credential issued by the Authorization Server allowing the client to obtain a new access token when the current access token becomes invalid or expires.

The implicit grant (or flow) is the only one that doesn't require the client to interact with the Token Endpoint of the OAuth 2.0 Server. Instead, the client receives the access token directly from the Authorization Endpoint.

Prerequisites

1. The client must be registered with the OAuth 2.0 Server and have a valid client ID. The client registration may lock down some of the token request parameters, such as the permitted grant types and token scope.

2. The client must have obtained a valid grant, e.g. an authorization code.

Bearer Assertion Grant

The Nimbus OAuth 2.0 SDK also supports the SAML 2.0 bearer and the JWT bearer grants.


Token request with a code grant

For a confidential client with a client_id and client_secret.

import com.nimbusds.oauth2.sdk.*;
import com.nimbusds.oauth2.sdk.auth;
import com.nimbusds.oauth2.sdk.http;
import com.nimbusds.oauth2.sdk.id;
import com.nimbusds.oauth2.sdk.token;

// Construct the code grant from the code obtained from the authz endpoint
// and the original callback URI used at the authz endpoint
AuthorizationCode code = new AuthorizationCode("xyz...");
URI callback = new URI("https://client.com/callback");
AuthorizationGrant codeGrant = new AuthorizationCodeGrant(code, callback);

// The credentials to authenticate the client at the token endpoint
ClientID clientID = new ClientID("123");
Secret clientSecret = new Secret("secret");
ClientAuthentication clientAuth = new ClientSecretBasic(clientID, clientSecret);

// The token endpoint
URI tokenEndpoint = new URI("https://cidaas.com/token");

// Make the token request
TokenRequest request = new TokenRequest(tokenEndpoint, clientAuth, codeGrant);

TokenResponse response = TokenResponse.parse(request.toHTTPRequest().send());

if (! response.indicatesSuccess()) {
    // We got an error response...
    TokenErrorResponse errorResponse = response.toErrorResponse();
}

AccessTokenResponse successResponse = response.toSuccessResponse();

// Get the access token, the server may also return a refresh token
AccessToken accessToken = successResponse.getTokens().getAccessToken();
RefreshToken refreshToken = successResponse.getTokens().getRefreshToken();

For a public client (with client_id only):


// Make the token request
TokenRequest request = new TokenRequest(tokenEndpoint, clientID, codeGrant);

TokenResponse response = TokenResponse.parse(request.toHTTPRequest().send());

if (! response.indicatesSuccess()) {
    // We got an error response...
    TokenErrorResponse errorResponse = response.toErrorResponse();
}

AccessTokenResponse successResponse = response.toSuccessResponse();

// Get the access token, the server may also return a refresh token
AccessToken accessToken = successResponse.getTokens().getAccessToken();
RefreshToken refreshToken = successResponse.getTokens().getRefreshToken();

Here’s the sample code to make a token request with the end-user's name and password credentials (password grant).


import com.nimbusds.oauth2.sdk.http;
import com.nimbusds.oauth2.sdk.id;
import com.nimbusds.oauth2.sdk.token;

// Construct the password grant from the username and password
String username = "alice@wonderland.net";
Secret password = new Secret("password");
AuthorizationGrant passwordGrant = new ResourceOwnerPasswordCredentialsGrant(username, password);

// The credentials to authenticate the client at the token endpoint
ClientID clientID = new ClientID("123");
Secret clientSecret = new Secret("secret");
ClientAuthentication clientAuth = new ClientSecretBasic(clientID, clientSecret);

// The request scope for the token (may be optional)
Scope scope = new Scope("read", "write");

// The token endpoint
URI tokenEndpoint = new URI("https://cidaas.com/token");

// Make the token request
TokenRequest request = new TokenRequest(tokenEndpoint, clientAuth, passwordGrant, scope);

TokenResponse response = TokenResponse.parse(request.toHTTPRequest().send());

if (! response.indicatesSuccess()) {
    // We got an error response...
    TokenErrorResponse errorResponse = response.toErrorResponse();
}

AccessTokenResponse successResponse = response.toSuccessResponse();

// Get the access token, the server may also return a refresh token
AccessToken accessToken = successResponse.getTokens().getAccessToken();
RefreshToken refreshToken = successResponse.getTokens().getRefreshToken();

Here's the sample code for token request with a client credentials grant (client acting on its own behalf).


import com.nimbusds.oauth2.sdk.*;
import com.nimbusds.oauth2.sdk.auth;
import com.nimbusds.oauth2.sdk.http;
import com.nimbusds.oauth2.sdk.id;
import com.nimbusds.oauth2.sdk.token;

// Construct the client credentials grant
AuthorizationGrant clientGrant = new ClientCredentialsGrant();

// The credentials to authenticate the client at the token endpoint
ClientID clientID = new ClientID("123");
Secret clientSecret = new Secret("secret");
ClientAuthentication clientAuth = new ClientSecretBasic(clientID, clientSecret);

// The request scope for the token (may be optional)
Scope scope = new Scope("read", "write");
// The token endpoint
URI tokenEndpoint = new URI("https://cidaas.com/token");

// Make the token request
TokenRequest request = new TokenRequest(tokenEndpoint, clientAuth, clientGrant, scope);

TokenResponse response = TokenResponse.parse(request.toHTTPRequest().send());

if (! response.indicatesSuccess()) {
    // We got an error response...
    TokenErrorResponse errorResponse = response.toErrorResponse();
}

AccessTokenResponse successResponse = response.toSuccessResponse();

// Get the access token
AccessToken accessToken = successResponse.getTokens().getAccessToken();

Authorization Server Metadata

Clients can use the Authorization Server Metadata Endpoint (a.k.a OAuth Discovery) to look up the information needed to interact with a particular OAuth server.

This includes aspects like finding the Authorization Endpoint, Authorization Server capabilities, and listing the supported scopes and client authentication mechanisms.

Metadata Value Mandate Description
issuer Required The Authorization Server's Issuer Identifier, is a URL that uses the https scheme without query or fragment components. Authorization Server Metadata is published at a location that is .well-known and derived from this issuer identifier.The issuer identifier is used to prevent Authorization Server mix-up or Mix-Up Mitigation.
authorization_endpoint Required This is the URL of the Authorization Server's Authorization Endpoint and is REQUIRED unless no grant types are supported for the Authorization Endpoint.
token_endpoint Required This is the URL of the Authorization Server's Token Endpoint and REQUIRED unless only the implicit grant type is supported.
jwks_uri Optional This is the URL of the Authorization Server's JWK which the client uses along with the signing key(s) to validate signatures from the Authorization Server. This URL MUST use the https scheme. The JWK Set may contain the server's encryption key or keys, which are used by clients to encrypt requests to the server. When both signing and encryption keys are made available, a "use" (public key use) parameter value is REQUIRED for all keys in the referenced JWK Set indicating each key’s intended usage.
registration_endpoint Optional This is the URL of the Authorization Server's OAuth 2.0 Dynamic Client Registration Endpoint.
scopes_supported Optional but RECOMMENDED The JSON array containing a list of the OAuth 2.0 scope values is supported by this Authorization Server. The servers May choose not to advertise some supported scope values even when this parameter is used.
response_types_supported Required The JSON array containing a list of the OAuth 2.0 response_type values is supported by this Authorization Server. The array values used are the same as those used with the response_types parameter defined by the OAuth 2.0 Dynamic Client Registration Protocol.
response_modes_supported Optional The JSON array containing a list of the OAuth 2.0 response_mode values is supported by this Authorization Server, as specified in the OAuth 2.0 Multiple Response Type Encoding Practices. When omitted, the default is [query,fragment]. The response mode value form_post is also defined in OAuth 2.0 Form Post Response Mode.
grant_types_supported Optional The JSON array containing a list of the OAuth 2.0 grant type values is supported by this Authorization Server. The array values used are the same as those used with the grant_types parameter defined by OAuth 2.0 Dynamic Client Registration Protocol. Omitting this will take the default value [authorization_code, implicit].
token_endpoint_auth_methods_supported Optional The JSON array containing a list of client authentication methods is supported by this Token Endpoint. Client authentication method values are used in the token_endpoint_auth_method. Omitting this will take the default value client_secret_basic which is the specified HTTP Basic Authentication Scheme specification of OAuth 2.0.
token_endpoint_auth_signing_alg_values_supported Optional The JSON array containing a list of the JWS signing algorithms ("alg" values) is supported by this Endpoint for the JWT signature used to authenticate the client at the Token Endpoint for the private_key_jwt and client_secret_jwt authentication methods. This metadata entry is mandatory if either of these authentication methods are specified in the token_endpoint_auth_methods_supported entry. No default Algorithms will be implied if this entry is omitted. Servers SHOULD support RS256 while the value none MUST NOT be used.
service_documentation Optional This is the URL of a page containing human-readable information used by developers to understand the Authorization Server. If the Authorization Server does not support Dynamic Client Registration, then the information on how to register clients, needs to be provided in this documentation.
ui_locales_supported Optional These include the languages and scripts supported for the user interface, represented as a JSON array of language tag values. Omitting this will lead to unspecified set of supported languages and scripts.
op_policy_uri Optional This URL is provided by the Authorization Server to the user registering the client to read the Authorization Server's requirements on how the client can use the data provided by the Authorization Server. The registration process SHOULD display this URL to the person registering the client if it is given. Despite the identifier op_policy_uri appearing to be OpenID-specific, its usage in this specification refers to a general OAuth 2.0 feature.
op_tos_uri Optional This is the URL that the Authorization Server provides to the user registering the client to read about the Authorization Server's Terms of Service. The registration process SHOULD display this URL to the person registering the client if it is given. Despite the identifier op_tos_uri, appearing to be OpenID-specific, its usage in this specification refers to a general OAuth 2.0 feature.
revocation_endpoint Optional This is the URL of the Authorization Server's OAuth 2.0 Revocation Endpoint.
revocation_endpoint_auth_methods_supported Optional The JSON array containing a list of client authentication methods is supported by this Revocation Endpoint. The valid client authentication method values are registered in the OAuth Token Endpoint Authentication Methods registry. Omitting this Endpoint will set the default as client_secret_basic -- the HTTP Basic Authentication Scheme for OAuth 2.0.
revocation_endpoint_auth_signing_alg_values_supported Optional The JSON array containing the list of the JWS signing algorithms ("alg" values) is supported by this Revocation Endpoint for the signature on the JWT used for client authentication for the private_key_jwt and client_secret_jwt authentication methods. This metadata entry MUST be present when specifying either of these authentication methods in the revocation_endpoint_auth_methods_supported entry. Omitting this entry will not imply any default algorithms. The value none MUST NOT be used.
introspection_endpoint Optional This is the URL of the Authorization Server's OAuth 2.0 Introspection Endpoint.
introspection_endpoint_auth_methods_supported Optional This Endpoint supports the JSON array containing a list of client authentication methods. The valid client authentication method values are those registered in the OAuth Token Endpoint Authentication Methods registry or those registered in the OAuth Access Token Types registry. These are distinct values for updated Registration Instructions for OAuth Access Token Types and OAuth Token Endpoint Authentication Methods in the OAuth Parameters registry. Omitting this Endpoint will require you to determine the set of supported authentication methods by other means.
introspection_endpoint_auth_signing_alg_values_supported Optional This Endpoint supports the JSON array containing a list of the JWS signing algorithms ("alg" values) for the signature on the JWT used to authenticate the client for the private_key_jwt and client_secret_jwt authentication methods. This metadata entry is mandatory if either of these authentication methods is specified in the introspection_endpoint_auth_methods_supported entry. Omitting this entry will not imply the default algorithms. The value introspection_endpoint_auth_methods_supported MUST NOT be used.
code_challenge_methods_supported Optional This server supports the JSON array containing a list of Proof Key for Code Exchange (PKCE) challenge methods. Code challenge method values are used in the code_challenge_method parameter. The valid code challenge method values are those registered in the PKCE Code Challenge Methods registry. Omitting this Authorization Server shall remove the support for PKCE.

Token Introspection Endpoint

The resource server needs to verify an access token when an OAuth 2.0 client makes a request to it. There is no specific method for the resource server to verify access tokens. It just mentions that it requires the resource and Authorization Servers to be coordinated.

Protected resources such as web APIs need to validate the access token in each received request, before serving it.

The access token will typically be of type Bearer and included in an Authorization header like this:

Authorization: Bearer [token-value]

In some cases, especially with small services, both the Endpoints are part of the same system. This makes the internal sharing of token information by these Endpoints easy (for example, in a database).

When these two Endpoints are on different servers in larger systems, proprietary and non-standard protocols need to be used for server communication.

The OAuth 2.0 Token Introspection extension defines a protocol that returns information about an access token. This token can be used by the resource servers or other internal servers.

The Token Introspection Endpoint is an OAuth 2.0 Endpoint that must return information about a token. It takes a parameter representing an OAuth 2.0 token and returns a JSON document representing the Meta information surrounding the token including whether it is currently active.

This will need to be built in the same place that the Token Endpoint lives. The two Endpoints need to work on a shared database or in the case of self-encoded tokens, they will need to share the secret key.

An active token is dependent on the Authorization Server but is commonly issued by the Authorization Server, is valid for use at the resource that makes the introspection call, has not expired, and has not been revoked.

A transport layer security mechanism MUST protect the introspection Endpoint.

Access Token Types

There are two kinds of Access Tokens encoded based on authorization parameters, such as the scope.

  • Identifier based-- This token represents a random, incomprehensible identifier for the token authorization in the Authorization Server's database.
  • Self-contained-- The authorization is encoded in the token itself and is cryptographically protected against tampering. JSON Web Token (JWT) is the common standard for that.

Token Information Request

This HTTP POST request shall contain just a parameter named “token”. This is done using parameters sent as application/x-www-form-urlencoded data.

The protected resource sends a parameter representing the token and additional context through optional parameters known by the protected resource to aid the Authorization Server’s response.

This Endpoint should not be made publicly available to developers. The end-user clients should be disallowed from using this Endpoint to prevent developer access to any privileged information. One way to protect the Endpoint is to encapsulate it in an internal server that is not accessible publically, or it could be protected with HTTP basic auth.

POST /token_info HTTP/1.1 Host: authorization-server.com

Authorization: Basic Y4NmE4MzFhZGFkNzU2YWRhN token =c1MGYwNDJiYmYxNDFkZjVkOGI0MSAgLQ

The parameters used in this request are given below:

Parameter Mandate Description
token Required This defines the string value of the token. For access tokens, this is the access_token value returned from the Token Endpoint defined in OAuth 2.0. This represents the refresh_token value for refresh tokens returned from the Token Endpoint as defined in OAuth 2.0.
token_type_hint Optional This refers to the hint on the token type submitted for introspection. The protected resource MAY pass this parameter to help the Authorization Server optimize the token lookup. If the server cannot locate the token using the provided hint, it MUST extend its search across all its supported token types. The Authorization Server MAY ignore this parameter when it detects the token type automatically. Values for this field are defined in the OAuth Token Type Hints registry for OAuth Token Revocation.

If the Authorization Server is unable to determine the token’s state without additional information, it returns an introspection response indicating that the token is not active.

Token Information Response

The response JSON object from the Token Introspection Endpoint shall include the properties listed below. Only the active property is mandatory; the rest are optional. You can also add additional properties in the response if you have additional information about a useful token.

Property Mandate Description
active Required This boolean value indicates whether or not the presented token is currently active. The value should be “true” if the token has been issued by this Authorization Server, has not been revoked by the user and has not expired.
scope Optional This token contains a JSON string with a space-separated list of scopes.
client_id Optional The OAuth 2.0 client is identified using this id to which the token was issued.
username Optional A human-readable identifier for the authorizer of this token.
exp Optional The Unix timestamp (integer timestamp, number of seconds since January 1, 1970 UTC) indicating the time when this token will expire.
iat Optional This is an Integer timestamp measured in the number of seconds since January 1 1970 UTC, to indicate the time this token was originally issued, as defined in the JWT.
nbf Optional This is an integer timestamp measured in the number of seconds since January 1 1970 UTC, to indicate the times this token is not to be used before, as defined in the JWT.
sub Optional This is usually a machine-readable identifier of the token authorizer which indicates the subject of the token, as defined in JWT.
aud Optional This is the service-specific string identifier or a list of string identifiers representing the intended audience of this token, as defined in the JWT.
iss Optional This is the string representing the issuer of this token, as defined in the JWT.
jti Optional String identifier for the token, as defined in JWT.

Example Response for the Introspection Endpoint

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

{
  "active": true,
  "scope": "read write email",
  "client_id": "J8NFmU4tJVgDxKaJFmXTWvaHO",
  "username": "aaronpk",
  "exp": 1437275311
}

Error Response

In a public domain, the Introspection Endpoint must first validate the authentication. If the protected resource uses OAuth 2.0 client credentials to authenticate to the introspection Endpoint and its credentials are invalid, the Authorization Server responds with an HTTP 401 and invalid_client response, which means it's Unauthorized.

Suppose the protected resource authorizes its call to the Introspection Endpoint using an OAuth 2.0 bearer token. The authorization token does not contain sufficient privileges or is otherwise invalid for this request. In that case, the Authorization Server responds with an HTTP 401 code for the OAuth 2.0 Bearer Token.

Please note that for an inactive or invalid token or a token the protected resource is not allowed to know about, a properly formed and authorized query is not considered an error response. In such circumstances, the Authorization Server MUST instead respond with an introspection response where the active field is set to false.

HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8

{
  "error": "invalid_client",
  "error_description": "The client authentication was invalid"
}

Returning the Inactive Token Status

This Endpoint shall return an Inactive Token flag rather than an error response in one of the following cases.

1. The token requested does not exist or is invalid.

2. The token expired.

3. The token was issued to a different client than is making this request.

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

{
  "active": false
}

You may extend this structure for specific implementations with your service-specific response names for top-level members of this JSON object. You must register the response names intended to be used across domains in the OAuth Token Introspection Response registry.

The Authorization Server MAY respond differently to different protected resources making the same request. Also, the protected resource MAY cache the response to improve performance and reduce the load on the Introspection Endpoint while making authorization decisions.

Access Token Introspection Request

Identifier-based access tokens are validated by making a network call to the Authorization Server using a standard protocol called OAuth 2.0 Token Introspection.

The protected resource will POST the token to the Authorization Server's Introspection Endpoint and return a JSON object with the token's parameters.

Please note that the introspection request cannot be made freely. It needs to be either,

  • Authenticated with credentials, or
  • Authorized with an access token.

Thus, for this particular interaction, the protected resource becomes an OAuth client, and the Authorization Server a protected resource.

JWT validation

JWT access tokens are validated locally by the protected resource, by checking their digital signature, issuer, expiration and if necessary other claims.

Here’s an example of an introspection request where the protected resource authenticates with a client_id and client_secret, which were obtained after registering as an OAuth client with the Authorization Server.

POST /token/introspect HTTP/1.1
Host: demo.cidaas.com
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
token=gai1iud5ohgh7aewaiV5riuzaiNgooWu

If the protected resource is allowed to access the Introspection Endpoint it will receive a JSON object with details about the token.

import java.net.URI;
import com.nimbusds.oauth2.sdk.*;
import com.nimbusds.oauth2.sdk.auth.*;
import com.nimbusds.oauth2.sdk.http.*;
import com.nimbusds.oauth2.sdk.id.*;
import com.nimbusds.oauth2.sdk.token.*;

// The introspection endpoint
URI introspectionEndpoint = new URI("https://demo.cidaas.com/token/introspect");

// The registered client credentials of the protected resource
ClientID clientID = new ClientID("s6BhdRkqt3");
Secret clientSecret = new Secret("gX1fBat3bV");

// Token to validate
AccessToken inspectedToken = new BearerAccessToken("gai1iud5ohgh7aewaiV5riuzaiNgooWu");

// Compose the introspection call
HTTPRequest httpRequest = new TokenIntrospectionRequest(
    introspectionEndpoint,
    new ClientSecretBasic(clientID, clientSecret),
    inspectedToken)
    .toHTTPRequest();

// Make the introspection call
HTTPResponse httpResponse = httpRequest.send();

The most important detail is the Boolean active parameter. If true , it means the token is valid and the JSON object will include other token details, such as its scope values. If false the token is either invalid or expired, hence the protected resource must return a 401 Unauthorized with invalid_token error code.

Example code for a valid token response

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8

{
  "active"     : true,
  "scope"      : "https://cidaas.com/accounts     
                  https://cidaas.com/groups",
  "client_id"  : "izad7cqy34bg4",
  "token_type" : "Bearer",
  "exp"        : 1448367412,
  "iat"        : 1448366912,
  "sub"        : "izad7cqy34bg4",
  "iss"        : "https://demo.cidaas.com",
  "jti"        : "thee5Quu"
}

Example response code for an expired or invalid token.

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8

{
  "active" : false
}

The Java Code for introspection response is given below.

import com.nimbusds.oauth2.sdk.*;
import com.nimbusds.oauth2.sdk.http.*;

TokenIntrospectionResponse response = TokenIntrospectionResponse.parse(httpResponse);

if (! response.indicatesSuccess()) {
    // The introspection request failed
    System.err.println("HTTP " + httpResponse.getStatusCode());
    System.err.println("Error: " + response.toErrorResponse().getErrorObject());
    return;
}

TokenIntrospectionSuccessResponse tokenDetails = response.toSuccessResponse();

if (! tokenDetails.isActive()) {
    System.out.println("Invalid / expired access token");
    return;
}
// Get the token Authorization details which are needed by the
// protected resource
System.out.println("Scope: " + tokenDetails.getScope());
System.out.println("Subject: " + tokenDetails.getSubject());
System.out.println("Client ID: " + tokenDetails.getClientID());

// If the token is going to be cached to save future lookups
// we'll need its expiration time
tokenDetails.getExpirationTime();

OAuth 2.0 Token Revocation Endpoint

A Token revocation request will invalidate the actual token and, if applicable, other tokens based on the same authorization grant.

From an end-user's perspective, OAuth is often used for logging into a specific site or application. This revocation mechanism allows a client to invalidate its tokens if the end-user logs out, changes identity, or uninstalls the respective application.

Notifying the authorization server that the token is no longer needed allows the Authorization Server to clean up data associated with that token, e.g., session data and the underlying authorization grant.

This behavior prevents a situation in which there is still a valid authorization grant for a particular client whose end-user is not aware. This way, token revocation prevents abuse of abandoned tokens. It facilitates a better end-user experience since invalidated authorization grants will no longer turn up in a list of authorization grants the Authorization Server might present to the end-user.

Token Revocation

Implementations MUST support the revocation of refresh tokens and SHOULD support the revocation of access tokens. The client makes a revocation request for a particular token by making an HTTP POST request to the token Revocation Endpoint URL. Clients MUST verify that the URL is an HTTPS URL.

It can be found at the revocation_endpoint of the resource server metadata and has the following form:

https://[base-server-url]/token/revoke

As this endpoint handles security credentials, the endpoint location needs to be obtained from a trustworthy source.

Since requests to the Token Revocation Endpoint result in the transmission of plaintext credentials in the HTTP request, URLs for token Revocation Endpoints MUST be HTTPS URLs. The Authorization Server MUST use Transport Layer Security (TLS).

Implementations MAY also support additional transport-layer security mechanisms that meet their security requirements.

Revocation Request

The client constructs the request by including the following parameters using the application/x-www-form-urlencoded format in the HTTP request entity-body.

Example: Revocation Request when the Token Type is available.

POST /token/revoke HTTP/1.1
Host: c2id.com
Content-Type: application/x-www-form-urlencoded
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
token=Ohw8choo.wii3ohCh.Eesh1AeDGong3eir&token_type_hint=refresh_token

Example: Revocation Request when the server will be let to determine the token type.

POST /token/revoke HTTP/1.1
Host: c2id.com
Content-Type: application/x-www-form-urlencoded
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
token=Ohw8choo.wii3ohCh.Eesh1AeDGong3eir

Token Revocation Process

The Authorization Server first validates the client credentials (in case of a confidential client). It then verifies whether the token was issued to the client making the revocation request. If this validation fails, the request is refused. The client receives one of the following error responses based on the error type by the Authorization Server.

400 Bad Request

Invalid or malformed request.

Example:

HTTP/1.1 400 Bad Request

401 Unauthorized

The request was denied due to an invalid or missing client authentication.

Example:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic

500 Internal Server Error

This means an internal server error has occurred. Please check the Connect2id server logs for more details.

Example:

HTTP/1.1 500 Internal Server Error

In the next step, the Authorization Server invalidates the token. The invalidation takes place immediately, which makes the token unusable again after the revocation.

Depending on the Authorization Server's revocation policy, the revocation of a particular token may cause the revocation of related tokens and the underlying authorization grant.

If the particular token is a refresh token and the Authorization Server supports the revocation of access tokens, then the Authorization Server SHOULD also invalidate all access based on the same authorization grant.

If the token passed to the request is an access token, the server MAY revoke the respective refresh token as well.

Note: The resource owners may revoke authorization grants, or the authorization server may invalidate tokens in order to mitigate security threats.

Revocation Response

The Authorization Server responds with the HTTP status code 200 if the token has been revoked successfully or if the client submitted an invalid token.

HTTP/1.1 200 OK

Important Considerations

  1. Revoking obtained Access and Refresh Tokens
  2. Clients can notify the cidaas server that a previously obtained refresh or access token is no longer needed. This allows the Authorization Server to clean up security credentials.

    A revocation request will invalidate the actual token and, if applicable, other tokens based on the same authorization grant.

    This is done by requesting the token Revocation Endpoint. The server will invalidate the specified token and, if applicable, other tokens based on the same authorization grant.

  3. Client Authentication
  4. Confidential clients must authenticate, and public clients must identify themselves as they would at the Token Endpoint.

    Resources

    1. Endpoint is: /token/revoke

    2. POST - Revokes an obtained refresh or access token.

    Header Parameters

    Parameter Mandate Description
    Authorization Optional Used for HTTP basic authentication of the client.
    Content-Type Required Must be set to OAuth application/x-www-form-urlencoded.

    Body with Form Parameters

    Parameter Mandate Description
    Token Required The token that the client wants to get revoked.
    token_type_hint Optional A hint about the type token submitted for revocation. Clients MAY pass this parameter in order to help the Authorization Server optimize the token lookup. If the server is unable to locate the token using the given hint, it MUST extend its search across all of its supported token types that include access_token and refresh_token.

    An Authorization Server MAY ignore this parameter, particularly if it is able to detect the token type automatically.


    This completes our discussion on cidaas OAuth 2.0 Services for Java SDK using Nimbus.

    If you face any issues with the Java SDK OAuth 2.0 Services configuration, please contact our support team for further assistance.



    results matching ""

      No results matching ""