# Authentication

To use the FibriCheck API, there are two levels of authentication:

* **Application authentication**: your application needs to have credentials to communicate with FibriCheck
* **User authentication**: the end user needs to have proper credentials to authenticate against FibriCheck

FibriCheck supports OAuth 1.0 and OAuth 2.0 mechanisms for authentication and authorization of users.&#x20;

## Authentication via OAuth 1.0

<figure><img src="https://550842036-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1VHmKXYQVUzvBkU504K0%2Fuploads%2Fce2ROJvZCoAA1S16dpnX%2Fdocs.fibricheck.com%20-%20User%20Authentication%20(1).png?alt=media&#x26;token=dace9f45-a88b-4531-b06e-7f3e569133d6" alt=""><figcaption></figcaption></figure>

When using OAuth 1.0, you need to add 2 sets of credentials to each request to the FibriCheck API:

* The **Consumer Key** and **Consumer Secret**, identify the application and are always required. We provide these credentials to you.
* The **Access Token** and **Token Secret** identify the user and are always required except for the user *registration* and *authentication* call. The authentication call that exchanges a e-mail/password combination for an Access Token and Token Secret is described below.

Keep in mind that an access token and token secret must always be used with the consumer key/secret they were generated with.

The remainder of this page discusses how to authenticate existing users, take a look [here](https://docs.fibricheck.com/introduction/users-and-registration) to learn more about registering new users.

### SDK

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

```dart
import 'package:flutter_fibricheck_sdk/flutter_fibricheck_sdk.dart';

// In this example we use the localstorage as a storage option for the credentials.
// Other packages or persistent storage methods can be used as well.
// More information: https://pub.dev/packages/localstorage
_storage = new LocalStorage('my_app');

_sdk = FLFibriCheckSdk.client("{consumerKey}", "{consumerSecret}");

void onConsentNeeded(List<Consent> documentsToSign) {
    for (var document in documentsToSign) {
      {
        // 1. Request approval from the user

        // 2. Pass the document back to the sdk
        _sdk.giveConsent(document);
      }
    }
  }

var res = await _sdk.authenticateWithEmail(
      ParamsOauth1WithEmail(email: "{userEmail}", password: "{userPassword}"),
      (consents) {
        _onConsentNeeded(consents);
      },
    );
    
//save token
storage.setItem('token', res.token);
//save token secret
storage.setItem('tokenSecret', res.tokenSecret);
```

The `tokenData` information can be used to authenticate the user for subsequent API calls.

```dart

var res = await _sdk.authenticateWithToken(
      ParamsOauth1WithToken(token: storage.getItem('token'), tokenSecret: storage.getItem('tokenSecret')), (consents) {
        _onConsentNeeded(consents);
      },)
```

{% endtab %}

{% tab title="React Native" %}
In the following example we use `@react-native-async-storage/async-storage` to store the credentials. You are free to use any other storage option in your application.&#x20;

```typescript
import AsyncStorage from '@react-native-async-storage/async-storage';

(async () => {
  const sdk = client({
    consumerKey: '',
    consumerSecret: '',
  });
  
  // Function that handles required consents 
  const onConsentNeeded = (legalDocumentsUpdated: Consent[]) => {
    legalDocumentsUpdated.forEach((document) => {
      // 1. Request approval from the user

      // 2. Pass the document back to the sdk
      sdk.giveConsent(document);
    });
  };

  const tokenData = await sdk.authenticate({
    email: '',
    password: '',
  }, onConsentNeeded);

  AsyncStorage.setItem('tokenData', JSON.stringify(tokenData));
})();
```

The `tokenData` information can be used to authenticate the user for subsequent API calls.

```typescript
import AsyncStorage from '@react-native-async-storage/async-storage';
(async () => {
  const tokenDataString = await AsyncStorage.getItem('tokenData');
  const tokenData = JSON.parse(tokenDataString);

  await sdk.authenticate({
    token: tokenData.key,
    tokenSecret: tokenData.secret,
  });
})();
```

{% endtab %}
{% endtabs %}

### REST API

## Authenticate using OAuth 1.0

<mark style="color:green;">`POST`</mark> `https://api.fibricheck.com/auth/v2/oauth1/tokens`

#### Headers

| Name                                            | Type   | Description                    |
| ----------------------------------------------- | ------ | ------------------------------ |
| Authorization<mark style="color:red;">\*</mark> | String | OAuth 1.0 Authorization Header |

#### Request Body

<table><thead><tr><th>Name</th><th width="68">Type</th><th>Description</th></tr></thead><tbody><tr><td>email<mark style="color:red;">*</mark></td><td>String</td><td></td></tr><tr><td>password<mark style="color:red;">*</mark></td><td>String</td><td></td></tr></tbody></table>

{% tabs %}
{% tab title="200: OK Successful authentication" %}

```javascript
{
    "applicationId": "5811ccc246e0fb0006efdc8d",
    "userId": "4a060568f0e0c45a11b03507",
    "token": "c7b2b7bd40b3d707b0b26005c23e8d0159d15f14",
    "tokenSecret": "a720e145acf6325bfb4fea698adfcabb6ddf52bf",
    "updateTimestamp": "2023-02-21T12:37:01.491Z",
    "creationTimestamp": "2023-02-21T12:37:01.491Z",
    "id": "83a3bf39c13dfeb75c6543b1"
}
```

{% endtab %}

{% tab title="401: Unauthorized Wrong user credentials provided" %}

```javascript
{
    "code": 106,
    "name": "AUTHENTICATION_EXCEPTION",
    "message": "this password email combination is unknown"
}
```

{% endtab %}

{% tab title="401: Unauthorized Invalid OAuth 1.0 credentials provided, or wrongly configured" %}

```javascript
{
    "code": 109,
    "name": "OAUTH_SIGNATURE_EXCEPTION",
    "message": "The oAuth signature is invalid"
}
```

{% endtab %}
{% endtabs %}

To implement the OAuth 1 protocol, additional parameters such as a request signature and nonce need to be added to the request. The [FibriCheck Postman workspace](https://docs.fibricheck.com/introduction/cloud-sdk/getting-started#rest-api) contains an example request to authenticate successfully.

Also, libraries exist for each platform that facilitates performing OAuth 1.0 requests, for example [node-oauth](https://www.npmjs.com/package/oauth) in the Node.JS ecosystem.

## Authentication via OAuth 2.0

When you choose to authenticate via OAuth 2.0 ([RFC 6749](https://datatracker.ietf.org/doc/html/rfc6749)), you will receive a `clientId` and `clientSecret`.

Each of the API calls below are protected using the `client_secret_basic` method. The `Authorization` header must be in the `Basic: encodedString` format, where the `encodedString` is a result of Base64 encoding of OAuth client’s `clientId:clientSecret`.

**Password grant flow**

```json
{
    "grant_type": "password",
    "username": "{user_email}",
    "password": "{user_password}"
}
```

**Refresh token grant flow**

After an initial login you can use the previously obtained refresh token to get a new token.

```
{
    "grant_type": "refresh_token",
    "refresh_token": "{refresh_token}"
}
```

The `access_token` in the result can be used to authenticate other calls using Bearer authentication.

## Get access tokens using the password grant flow

<mark style="color:green;">`POST`</mark> `https://api.fibricheck.com/auth/v2/oauth2/tokens`

{% tabs %}
{% tab title="200: OK " %}

```json
{
    "access_token": "78f33670236eaa4181edac918c871cd474b9e6fa",
    "token_type": "bearer",
    "expires_in": 299.996,
    "refresh_token": "11011eabe30371cfebbb401c36531bd1451f6121",
    "user_id": "6422a0d97db02e7197c8dfcf",
    "application_id": "64f242bdbc3be60b821863ed"
}
```

{% endtab %}
{% endtabs %}

{% hint style="danger" %}
With every new access token, a new refresh token is provided. Make sure always to store the latest refresh token.
{% endhint %}

{% hint style="info" %}
**Token Lifetime**

The different OAuth2.0 tokens have a limited lifetime

* Access token: 5 minutes
* Refresh token: until used or until revoked
  {% endhint %}

## Disable Authentication

### Rest API

You can disable user authentication/access by removing their authentication tokens. This means the user will be logged out and must log in again to continue.

Execute an API call with the following payload to remove their authentication tokens:

```json
{  
    "data": {
        "command": "delete-authentication",
        "data": {
          "userId": "{userId}",
          "groupId": "{groupId}"
        }
    }
}
```

## Delete User Authentication

<mark style="color:green;">`POST`</mark> `https://api.fibricheck.com/tasks/v1/functions/integration/execute`

#### Request Body

| Name   | Type   | Description |
| ------ | ------ | ----------- |
| data\* | String | Payload     |

{% tabs %}
{% tab title="200: OK " %}

{% endtab %}
{% endtabs %}
