# Authorisation

After registration, your application can acquire credentials on behalf of your users in order to make requests.
This is done by initiating Transact's OAuth flow from within your application.

## About OAuth 2.0

The Transact API uses [OAuth 2.0](https://oauth.net/2/), an industry standard protocol that allows an end
user to authorise your application to perform certain actions on behalf of the user, without the user's credentials
being shared with the application itself.

It allows your application to gain consent to perform actions (such as retrieval of data) on behalf of a
Transact user (e.g. an adviser firm, adviser network or investment manager).

Transact Online acts as an intermediary between your application and the
Transact user, ensuring that the user's credentials are kept secure.

### Authorisation Code Flow

The OAuth 2.0 specification contains a collection of different flows. The specific flow Transact has implemented is
called the **OAuth 2.0 Authorisation Code Flow**. This allows for your application to request permission from the
user to perform actions on their behalf.

Below is an explanation of the formal roles involved:

| **Roles**            | **Description**                                                                                                                                                                                                                                                  |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Protected Resources  | Transact data belonging to the user (Resource Owner).                                                                                                                                                                                                            |
| Client               | The software provider (you) are the Client. It is your application that requires access to the protected resources. The application must be server-side as it must submit a client secret to authenticate itself. It is critical that the secret is kept secure. |
| Resource Owner       | The user (e.g. adviser firm, adviser network, investment manager).                                                                                                                                                                                               |
| Authorisation Server | The Transact server that processes the requests from the Client to acquire refresh tokens and access tokens.                                                                                                                                                     |
| Resource Server      | The Transact server that processes the requests from the Client to access the Resource Owner's data.                                                                                                                                                             |
| User-Agent           | A web browser used by the Resource Owner (user).                                                                                                                                                                                                                 |

For more details on the Authorisation Code Flow and OAuth 2.0, please refer to [RFC 6749](https://datatracker.ietf.org/doc/html/rfc6749).

## Acquiring an access token

All requests to the Transact API must contain a valid access token, which proves your right to perform
certain actions on behalf of the Resource Owner.

To acquire an access token, follow the OAuth flow:

1. Direct the Resource Owner to Transact's Authorisation Endpoint, which will then pass an authorisation code back to your application.
2. Exchange the authorisation code for an access token via Transact's Token Endpoint.

### Get an authorisation code

When the Resource Owner initiates the OAuth flow from within your application, the User-Agent must be redirected to
Transact's Authorisation Endpoint[^1] with the following query parameters:

| Query Parameter Name | Value                                                                                                                                                      |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `client_id`          | Your client ID acquired as part of the registration process.                                                                                               |
| `response_type`      | Must always be `code`.                                                                                                                                     |
| `state`              | An opaque value generated by you to maintain a binding between the request and the User-Agent's authenticated state within your application.               |
| `scope`              | The scopes being requested as part of the access request, separated by a URL encoded space character `%20`. For example, `entity.read%20transaction.read`. |
| `redirect_uri`       | This must match one of your pre-registered Redirect URIs.                                                                                                  |

The Resource Owner will be presented with a Transact login page.

:::info

Only a Transact adviser firm, adviser network or investment manager _super user_ is permitted to grant your application access to Transact data.

:::

On login, the Resource Owner can be presented with the following on-screen error messages. These error messages are not returned to your application.

| **On-screen Error**                                                                       | **Description**                                                                                                                                                                     |
| ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| The client you are using is not authorised to access our public services.                 | The request `client_id` URL parameter is blank, or does not exist; or the request `redirect_uri` URL parameter is blank, or is not registered with Transact against your client ID. |
| You must have adviser firm, network or investment manager Super User privileges.          | The user granting consent does not have super user privileges, or is an unsupported user type.                                                                                      |
| To continue, you must enable Multi-Factor Authentication by logging into Transact Online. | The user granting consent does not have multi-factor authentication enabled.                                                                                                        |

Once the Resource Owner has logged in successfully without any of the above errors occurring, Transact will do further validation. If further errors occur, Transact will redirect the User-Agent back to your application via your Redirect URI. Below is the list of errors that can be included in the redirect.

| **Error**                                                      | **Description**                                                                                                                 |
| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `{{redirect_uri}}?error=invalid_state&state=`                  | The request `state` URL parameter is blank.                                                                                     |
| `{{redirect_uri}}?error=unsupported_response_type&state=xxxx`  | The request `response_type` URL parameter is not `code`.                                                                        |
| `{{redirect_uri}}?error=invalid_scope&state=xxxx`              | The request `scope` URL parameter is invalid (e.g. blank, duplicated, or not recognised by Transact).                           |
| `{{redirect_uri}}?error=missing_attestation&state=xxxx`        | The attestation is missing or lapsed and will need to be completed under _Housekeeping > Terms of Business_ on Transact Online. |
| `{{redirect_uri}}?error=forbidden_requested_scopes&state=xxxx` | The Resource Owner's role (user type) is not sufficient to grant one or more of the requested scopes.                           |
| `{{redirect_uri}}?error=access_denied&state=xxxx`              | The Resource Owner has denied your request.                                                                                     |

Once the user has granted access, Transact will redirect the User-Agent back to the provided Redirect URI. An
authorisation code will be returned within the Redirect URI as parameter `code`. Your provided `state` value will also
be included.

For example, if your redirect URI is `https://example.com/callback`, the User-Agent will be redirected to
`https://example.com/callback?code=NewCode&state=YourStateValue`.

:::tip

To protect your application from Cross-Site Request Forgery (CSRF) attacks, we strongly suggest you
check the validity of this request by verifying that the `state` value matches the User-Agent's authenticated state.

:::

### Exchange for an access token

Once you have the authorisation code, it can be exchanged for a new refresh token and access token via Transact's
Token Endpoint[^2]. The authorisation code is only valid for a short window of time, so it should be used as soon as
possible. It will be invalidated once used.

When calling the Token Endpoint, the application is authenticated by client ID and client secret using HTTP Basic
Authentication. The following fields must be provided in the request body using the `application/x-www-form-urlencoded`
content type:

| Field Name     | Value                                                                                  |
| -------------- | -------------------------------------------------------------------------------------- |
| `grant_type`   | Must be `authorization_code`.                                                          |
| `code`         | The authorisation code acquired in the previous step.                                  |
| `redirect_uri` | Must match the Redirect URI used in the initial request to the Authorisation Endpoint. |

:::warning

If we receive a request with an incorrect client secret, the existing registered secret will be invalidated. You will
need to log in to TOL and [generate a new one](registration.md#generate-your-client-secret).

:::

If successful, the JSON body of the response will be as follows:

```json
{
  "access_token": "<access_token>",
  "token_type": "Bearer",
  "access_token_expires_in": "<expire_period_in_seconds>",
  "refresh_token": "<refresh_token>",
  "scope": "<scope>",
  "refresh_token_expires_in": "<expire_period_in_seconds>"
}
```

The returned `access_token` can now be used to make requests to the Transact API.
The access token expires after a reasonably short period of time, after which time a new access token must be acquired
by either:

- using the `refresh_token` (see next sections) or
- repeating the OAuth process.

:::danger

Please take note of the refresh token `expires_in` value (see also 'Refresh Token Lifespan' under
[Environments](../advanced/environments.md)).
It is good practice to note the expiry length of refresh tokens, and remind the user to reauthorise before expiry
if continuity of service is important. See [Refresh Token Expiry](#refresh-token-expiry).

:::

:::tip

The access token also contains encoded information such as the Resource Owner's name, role, and Transact number.
For information about reading this information within your application, see [Token Claims](../advanced/tokens.md).

:::

## Using a refresh token

Once an access token has expired, you will need to acquire a new access token. If the accompanying refresh token
has not expired, it can be used to obtain a new access token via the same Token Endpoint.

As before, when calling the Token Endpoint the application is authenticated by client ID and client secret using HTTP
Basic Authentication. The following fields must be provided in the request body using the
`application/x-www-form-urlencoded` content type:

| Field Name      | Value                                               |
| --------------- | --------------------------------------------------- |
| `grant_type`    | Must be `refresh_token`.                            |
| `refresh_token` | The refresh token acquired in the previous section. |

If successful, the JSON body of the response will be as follows:

```json
{
  "access_token": "<access_token>",
  "token_type": "Bearer",
  "expires_in": "<expire_period_in_seconds>",
  "scope": "<scope>"
}
```

## Refresh token expiry

Transact's policy in regards to permissions granted via OAuth is that a Resource Owner must remain aware that
they are sharing data with your application. In line with this, refresh tokens expire after a period of time.
This requires the Resource Owner to periodically reauthorise your application's access.

If your application logic includes a scheduled process (e.g. retrieving valuations automatically each day), you may
deem it essential to proactively remind the user to reauthorise. However, if your application only calls the Transact API when a user interacts with your application, you may prefer to only prompt the user to reauthorise after expiry.

## Token revocation

Please be aware that Transact provides Resource Owners with the ability to revoke permissions granted to your application, effectively
invalidating any refresh tokens and access tokens you possess on their behalf. In this scenario, your application needs to trigger the OAuth flow again
in order to regain permissions.

[^1]: See [Environments](../advanced/environments.md). The UAT Authorisation Endpoint is https://authdemo.transact-online.co.uk

[^2]: See [Environments](../advanced/environments.md). The UAT Token Endpoint is https://authdemo.transact-online.co.uk/token
