# Obtain a Token

# Description

Obtains an OAuth 2.0 access token and possibly also an OpenID Connect ID token. This operation can be invoked as part of an OAuth 2.0 or OpenID Connect authorization code grant flow or via an OAuth 2.0 client credentials grant flow.

When the authorization code grant flow is used, the obtained access token represents the authorization granted by a user to the application making the call for accessing certain resources or services on this user's behalf (identity data, signature identities, etc.). To obtain the token, the application must present the authorization code obtained with the Obtain Authorization operation.

If the authorization code was obtained via OpenID Connect authentication, an ID token will be obtained along with the access token.

When the client credentials grant flow is used, the obtained access token demonstrates the administrative authorization of the application making the call for accessing certain resources or services (i.e., without direct intervention of the resource's owner), or for accessing resources of the application. The token may be of two types:

- Token associated to an identity domain but not to a user: If the authorization server that processes the request is associated to an identity provider, the token issued will be associated to the identity domain of the IdP. A token of this type allows administrative access to user resources in the domain.

- Token not associated to an identity domain or a user: This type of token is issued when the authorization server that processes the request is not associated to an identity provider. A token of this type can be used for accessing resources not associated to users or to user resources of any domain.

Use of client credentials grant requires that the application can be authenticated. For this reason, this flow can only be enabled for server-based Web applications and not for installed (native) applications.

# Request

To obtain the token, the client application must send a request like the following to TRIDENT using TLS. Note that unlike in the exchange described in Obtain Authorization, this request is sent directly from the client application to the TRIDENT and does not go via the browser.

`POST /trustedx-authserver/oauth/token`

## Alternative Endpoints

It is also possible to use the `/trustedx-authserver/oauth/{as}/token` endpoint. However, this should only be done if the TRIDENT administrator has associated your application with several Authorization Servers that recognize all the values included in the scope field of the authorization request for Authorization Code Grant flows (which is an advanced scenario). In any other case, you should point the browser to the `/trustedx-authserver/oauth/token` endpoint.

On the other hand, to keep backward compatibility, the following endpoints can also be used:

- `/trustedx-authserver/{as}/oauth/token`

- `/trustedx-authserver/{idp}/oauth/{as}/token`

Remember that these two endpoints should never be used for new integrations as they are supported only to prevent legacy integrations from breaking down, and supporting them may be terminated in the future.

## Parameters

Name | Type | Usage | Description
`as` | path | Optional. It should only be used if the application is associated with more than one Authorization server that supports the requested scope for Authorization Code Grant flows. | Identifier of the TRIDENT authorization server from which the token is requested (Server ID field of one of the Authorization server entities). For the authorization code grant flow, it must coincide with the authorization server that generated the authorization code. If this parameter is not specified, TRIDENT selects the authorization server in one of the following ways: For the authorization code grant flow, it selects the authorization server that issued the authorization code specified in the code field of the body of the request. For the client credentials grant flow, it selects one of the servers of the client application that supports this flow for the scopes requested (for all the values included). If no entity qualifies or multiple do, an error is returned.
`idp` | path | Optional (it can only be present when the `as` parameter is also present). | Identifier of the identity provider associated with the authorization server indicated by the `as` parameter.

## Content-Type Header

`Content-Type: application/x-www-form-urlencoded; charset=UTF-8`

## Body

The content of the request varies according to the type of OAuth 2.0 flow in which the token is requested:

- Content in the case of the authorization code grant flow

- Content in the case of the client credentials grant flow

### Content in the Case of the Authorization Code Grant Flow

Property | Usage | Description
`grant_type` | Required | Must have the `authorization_code` value.
`code` | Required | The authorization code received in the previous authorization response (see Obtain Authorization).
`code_verifer` | Conditionally required | Character string from which the value of the `code_challenge` included in the authorization request that obtained the authorization code (`code`) corresponding to the token requested was derived. This string of characters has to be generated randomly with high entropy.
`redirect_uri` | Optional | URI where the authorization response was received with the authorization code. Must match the `redirect_uri` parameter of the authorization request and must be omitted if it is also omitted in the authorization request.

### Content in the Case of the Client Credentials Grant Flow

Property | Usage | Description
`grant_type` | Required | Must have the value `client_credentials.`
`scope` | Optional | List values representing the scope of the authorization (resources) the application wants to obtain. If this parameter is not specified, the default scopes defined for the selected authorization server entity enabled for client credentials grant enabled are taken.

## Authentication of the Client Application

Public client applications (installed/native applications) do not need to authenticate to use this operation.

The application must authenticate using the HTTP basic authentication scheme in other cases. As credentials, the application must specify the identifier and secret assigned to the application during its registration in TRIDENT (the Client identifier and Client secret fields of the Client application), encoded as specified by OAuth 2.0.

Specifically, the application must include an `Authorization` header with the following structure.

`Authorization: Basic {credentials}`

Where {`credentials`} is the result of encoding the client identifier of the application (`client_id`) and its secret `(client_secret`) as follows:

`base64(url_encode(utf8(client_id)) ':' url_encode(utf8(client_secret)))`

The meaning of the above pseudocode is:

- Encode `client_id` first in UTF-8 and then according to the URL character escape rules.

- Encode `client_secret` first in UTF-8 and then according to the URL character escape rules.

- Concatenate both using colons (“:”) as the separator.

- Encode the resulting string in base64 without line breaks.

The rules for escaping characters in URLs are those defined for the application/x-www-form-urlencoded MIME format in the HTML specification that must be applied to the bytes resulting from encoding the identifier or secret in UTF-8. See the example below.

Note

The HTTP basic authentication scheme defined in RFC 2617 does not specify that the credentials must be encoded in UTF-8 and in URL format. The use of these additional encoding rules is part of OAuth 2.0. If a software library or tool that generates the `Authorization` header as per RFC 2617 is used, keep this in mind, especially when the identifier or secret contains extended symbols or characters.

## Example

This example shows a request for obtaining a token sent by an application with the demapp identifier and the "`om+4a_.CE-qüKC mK:3&V`" secret. Ellipses and line breaks have been included to facilitate reading.

`POST /trustedx-authserver/oauth/token HTTP/1.1`
`Host: trustedx.demo.com:443`
`Authorization: Basic ZGVtb2FwcDpvbSUyQjRhXy5DRS1xJUMzJUJDS0MrbUslM0EzJTI2Vg==`
`Content-Type: application/x-www-form-urlencoded; charset=UTF-8`
`grant_type=authorization_code&`
`redirect_uri=https%3A%2F%2Fwww.demoapp.com%2Foauth%2Fback&`
`code=4515...e0ba`

Before they were included in the `Authorization` header, the client identifier and secret were encoded in UTF-8 in URL format. Specifically, the value of the header was generated as `base64("demoapp:om%2B4a_.CE-q%C3%BCKC+mK%3A3%26V")` after the following conversions were applied:

- The "+" character was converted to "%2B".

- The "ü" character, which is encoded in UTF-8 with two bytes, was converted to "%C3%BC".

- The " " (space) was converted to "+" (TRIDENT also accepts encoding it as "%20").

- The ":" character was converted to "%3A".

- The "&" character was converted to "%26".

The rest of the characters of the identifier and the secret used in this example do not need conversions.

# Response

In response, TRIDENT issues a bearer-type OAuth 2.0 access token and returns it in a JSON structure. The application can later use this token to invoke TRIDENT's REST services.

If the operation is performed in the course of an OpenID Connect authentication (if the operation is part of an Authorization Code Grant flow and the scope of the Obtain Authorization request contained the `openid` value), the TRIDENT will provide an OpenID Connect token ID along with with the access token.

Note

Suppose the TRIDENT provides an OpenID Connect token ID in the response. In that case, it is recommended that the application save it to be used later as the value of the `id_token_hint` parameter in an eventual Log out request.

## Status-Line

`HTTP/1.1 200 OK`

## Content-Type Header

`Content-Type: application/json;charset=UTF-8`

## Body

JSON object containing the access token, associated information, and, if the openid value was included in the scope requested, an ID token.

`{`
`"access_token" : {string},`
`"token_type" : "Bearer",`
`"expires_in" : {number},`
`"scope" : {string},`
`"id_token" : {string}`
`}`

Property | Description
`access_token` | Access token generated by TRIDENT. The token has the characteristics specified in the configuration of the authorization server that processed the request and consists of a random string of the number of bytes specified in the Access token number of random bytes (by default, 32), encoded in hexadecimal.
`token_type` | Type of access token. Always has the `"Bearer"` value.
`expires_in` | Lifetime (in seconds) of the access token. The application must perform the access the token authorizes before the token expires. This value can be configured in the Token timeout option of the authorization server (by default, 120 seconds). Once this timeout has expired, the token becomes invalid, and the application must obtain another one if it wants to continue invoking the protected services.
`scope` | Scope of the access token (with all its values separated by spaces).
`id_token` | ID token issued. This property is only present for authorization code grant flow and if the application requested the `openid` scope in the obtain authorization operation. See Claims of the ID Tokens for details on the ID tokens issued by TRIDENT.

## Example: Issue of an Access Token

This example shows a response that contains an access token for the `urn:safelayer:eidas:sign:identity:use:server` scope (use of the user's server signing identities). The token is valid for 120 seconds. Ellipses have been included in the value of the token to facilitate reading.

`HTTP/1.1 200 OK`
`Content-Type: application/json;charset=utf-8`
`Cache-Control: no-store, no-cache, must-revalidate`
`Pragma: no-cache`
`{`
`"access_token" : "a2b4...6daf",`
`"token_type" : "Bearer",`
`"expires_in" : 120,`
`"scope" : "urn:safelayer:eidas:sign:identity:use:server"`
`}`

## Example: Issue of an Access Token and an ID Token

In this example, an OpenID Connect ID token was issued along with the access token. The scope of the access token is associated is `openid`, `profile` and `email`. Ellipses have been included in the value of both tokens to facilitate reading.

`HTTP/1.1 200 OK`
`Content-Type: application/json;charset=utf-8`
`Cache-Control: no-store, no-cache, must-revalidate`
`Pragma: no-cache`
`{`
`"access_token" : "ffec...d8fd",`
`"token_type" : "Bearer",`
`"expires_in" : 120,`
`"scope" : "openid profile email"`
`"id_token" : "eyJhbGciOiJSUzI1NiIsImtpZCI6Ijg3ZmVkNjM2Y2VlO..."`
`}`

# Error response

If the token issue request cannot be processed (because the request is invalid, the authentication of the client application fails, the authorization code expired, etc.), TRIDENT returns an error response in the format defined by OAuth 2.0. The response normally (except in the cases described below) has an `HTTP 400 (Bad Request)` status code and a JSON data structure with the following parameters:

- `error`: Error code. See the standard and the list below for more details.

- `error_description`: Additional description of the error. Not required.

- `error_uri`: Always omitted. TRIDENT does not use this parameter.

The following are the values supported and the meanings of error and error_description (if there is one) for some of the common errors:

- `invalid_client, unsupportedAuthenticationScheme`: The authentication scheme specified in the Authorization HTTP header is not supported. TRIDENT currently only supports the basic scheme (HTTP Basic authentication scheme) specified in RFC 2617. In this case, the HTTP status code returned is 401 (Unauthorized).

- `invalid_client, invalidCredentials`: The client application cannot be authenticated with the credentials included in the Authorization HTTP header. This may be because there is no Client Application configured in the TRIDENT with the identifier specified or because the entity exists, but the secret does not match the configured secret. The HTTP status code returned is 401 `(Unauthorized)`.

- `unsupported_grant_type`: The value of the `grant_type` parameter in the request is not supported. TRIDENT currently only supports the `authorization_code` type.

- `invalid_grant, codeNotFound`: The authorization code specified in the code parameter of the request was not issued in a recent authorization response or has expired.

- `invalid_grant, expiredCode`: The authorization code specified in the code parameter of the request has expired.

- `invalid_grant, codeNotIssuedToClientId`: The authorization code specified was issued for a different client application than that identified in the Authorization HTTP header.

- `invalid_grant, redirectUriMismatch`: The authorization code specified was issued for an authorization request associated to a redirect URL different from the URL specified in the `redirect_uri` parameter of the request.

- `invalid_scope`: Only for the client credentials grant flow. One of the values of the scope requested by the application is not included in this list of scopes provided by the authorization server or has not been enabled for the client credentials grant. This error also occurs if the application did not request any scope and the server has no default scope defined for this type of grant.

If an internal error occurred in the server, a JSON response is not returned. Instead, an `HTTP 500 (Internal Server Error)` status code is returned In these cases, the TRIDENT administrator must browse the log records to identify the problem.

## Example

Below is an example of a token issue error response. Ellipses and line breaks have been included to facilitate reading.

`HTTP/1.1 401 Unauthorized`
`Content-Type: application/json;charset=utf-8`
`Cache-Control: no-store, no-cache, must-revalidate`
`Pragma: no-cache`
`{`
`"error" : "invalid_client",`
`"error_description" : "invalidCredentials"`
`}`