> For the complete documentation index, see [llms.txt](https://docs.bloqifi.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.bloqifi.com/reference/api-reference/authentication.md).

# Authentication

How to use JWT to authenticate with our RESTful API

To authenticate a request, a client application must send a JSON Web Token (JWT) in the authorization header of the HTTP request to our back-end RESTful API.

Bloqifi RESTful API validates a JWT in a performant way by using the JWT issuer's [JSON Web Key Set (JWKS)](https://tools.ietf.org/html/rfc7517).

Although this example is somewhat basic, it should provide a clear idea of our logic with JWT. As stated above, any interaction with our secure RESTful API would start with a login request, which would look something like the following:

## Generate JSON Web Token (JWT)

<mark style="color:green;">`POST`</mark> `https://api.bloqifi.com/v0/token`

#### Request Body

| Name                                       | Type   | Description                                |
| ------------------------------------------ | ------ | ------------------------------------------ |
| email<mark style="color:red;">\*</mark>    | String | \[a-z0-9.\_%+-]+@\[a-z0-9.-]+.\[a-z]{2,4}$ |
| password<mark style="color:red;">\*</mark> | String | (?=.*\d)(?=.*\[a-z])(?=.\*\[A-Z]).{6,}     |

{% tabs %}
{% tab title="200: OK Welcome back.." %}

```javascript
{
    accessToken: token, // 30 minutes expiry
    refreshToken: token // 1 day expiry
}
```

{% endtab %}

{% tab title="401: Unauthorized Incorrect email or password or both" %}

```javascript
{
    message: 'Authentication failed. Invalid user or password.'
}
```

{% endtab %}

{% tab title="202: Accepted Pending email confirmation" %}

```javascript
{
    message: 'Authentication failed. Email not verified.'
}
```

{% endtab %}

{% tab title="201: Created Pending user confirmation" %}

```javascript
{
    message: 'Authentication failed. Identity not verified.'
}
```

{% endtab %}

{% tab title="404: Not Found Incorrect email or password or both" %}

```javascript
{
    message: 'Authentication failed.'
}
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="curl" %}

```
curl -X POST https://api.bloqifi.com/v0/token \
-H "Content-Type: application/json" \
-d '{"email":"my_email","password":"my_password"}'
```

{% endtab %}
{% endtabs %}

The payload is as follows:

```
{
    'email': 'my_email'
    'password': 'my_password'
}
```

Assuming the credentials are valid, the system would return a new `JSON Web Token`. (`Access & Refresh`) Let’s go over the details of this token. Particularly, let’s think about the information inside our payload. Some interesting options could be:

* `Email`: Contains the email of the logged in user, which is especially useful since we might want to show that in our UI
* `Exp`: We’ll only allow our new token to be used for the next fifteen minutes, which is about how long users should need it on a daily basis, before requesting a new access token based on their refresh token.
* `Status`: Contains the status of the logged in user, which is useful since we might need to verify this account.

To keep things simple, we’ll use an HS256 algorithm for encoding the data.

Let’s consider what the different sections of our token should look like:

**Header**: with the type (JWT) and type of coding.

```javascript
{
    alg: 'HS256',
    typ: 'JWT'
}
```

**Payload**: It is where the user’s information will be found that will allow the server to discern whether or not it can access the requested resource.

```javascript
{
    email: 'my_email@example.com',
    firstName: 'First Name',
    lastName: 'Family Name',
    exp: 1550946689,
    iat: 1550946689,
    role: {
        name: 'Tier 1',
        permissions: Array[{}]
    }
    permissions: Array[{}],
    status: 200
}
```

Any further requests sent by the client app will contain this same access token. In turn, the token will be validated by the server, and the result compared with the signature portion of the token.

In a typical JWT request, you’ll pass the token as part of the authorization header on the client-side after the client logged in, like `Authorization: Bearer`.

Doing so would prevent, for example, someone from meddling with the message’s payload and changing the role to Admin, allowing a fake or even a valid non-admin user, to execute a privileged action like issuing a payment to create a bloq.

### Types of token

There are many types of token, although in authentication with JWT the most typical are **access token and refresh token.**

* **Access token**: It contains the information our server needs to know so the user / device can access the resource their are requesting or not.
* **Refresh token**: The refresh token is used to generate a new access token.

## Refresh access token

The refresh token requires greater security when it is stored than the access token, as if it were stolen by third parties, they could use it to obtain new access tokens and access the protected resources of the application.

## Exchange refresh token for access token

<mark style="color:orange;">`PUT`</mark> `https://api.bloqifi.com/v0/token`

#### Headers

| Name                                           | Type   | Description      |
| ---------------------------------------------- | ------ | ---------------- |
| Content-Type<mark style="color:red;">\*</mark> | String | application/json |

#### Request Body

| Name                                    | Type   | Description     |
| --------------------------------------- | ------ | --------------- |
| token<mark style="color:red;">\*</mark> | String | ${refreshToken} |

{% tabs %}
{% tab title="201: Created Access token available" %}

```javascript
{
    accessToken: token, // 30 minutes expiry
}
```

{% endtab %}

{% tab title="401: Unauthorized No payload, only header" %}

{% endtab %}
{% endtabs %}

## Revoke refresh token

Should you need to revoke a refresh token for any reason, this endpoints makes it possible.

## Revoke refresh token

<mark style="color:red;">`DELETE`</mark> `https://api.bloqifi.com/v0/token`

#### Headers

| Name                                            | Type   | Description           |
| ----------------------------------------------- | ------ | --------------------- |
| Content-Type<mark style="color:red;">\*</mark>  | String | application/json      |
| Authorization<mark style="color:red;">\*</mark> | String | Bearer ${accessToken} |

#### Request Body

| Name                                    | Type   | Description     |
| --------------------------------------- | ------ | --------------- |
| token<mark style="color:red;">\*</mark> | String | ${refreshToken} |

{% tabs %}
{% tab title="204: No Content Token removed" %}

{% endtab %}

{% tab title="400: Bad Request Failed" %}

```javascript
{
    message: 'Failed to revoke token..'
}
```

{% endtab %}
{% endtabs %}

## Generate refresh token

Enabled user generated refresh token with predefined expiry

## Generate refresh token

<mark style="color:purple;">`PATCH`</mark> `https://api.bloqifi.com/v0/token`

#### Headers

| Name                                            | Type   | Description           |
| ----------------------------------------------- | ------ | --------------------- |
| Content-Type<mark style="color:red;">\*</mark>  | String | application/json      |
| Authorization<mark style="color:red;">\*</mark> | String | Bearer ${accessToken} |

#### Request Body

| Name                                    | Type   | Description       |
| --------------------------------------- | ------ | ----------------- |
| exp<mark style="color:red;">\*</mark>   | Number | Number of seconds |
| token<mark style="color:red;">\*</mark> | String | ${refreshToken}   |

{% tabs %}
{% tab title="201: Created New refresh token available" %}

```javascript
{
    refreshToken: token, // user-defined expiry
}
```

{% endtab %}

{% tab title="400: Bad Request Failed" %}

```javascript
{
    message: 'Failed to generate token..'
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
**Good to know:** Be careful with this endpoint. Do not generate refresh tokens with unreasonable expiry.

Keep the time limit within use case.

**Hint**: `1` day is `86400` seconds
{% endhint %}
