# Authentication

Requests between Ergonode and App are signed using [JWT](https://jwt.io/) tokens.

These tokens allow the safe exchange of custom data(claims) between two parties.

The token contains claims describing the context of the execution - what specific installation the token is referencing etc.

The token is always available in `X-APP-TOKEN` HTTP header with a signature signed using HMAC SHA-256.

{% hint style="info" %}
Note you should not be forced to implement JWT authentication on your own.

There are multiple well-developed and acknowledged open-source solutions to handle the issue.
{% endhint %}

## Handshake

To authenticate the token firstly, on App installation, a handshake is exchanged.

Handshake is a request to `[POST] /handshake` path of [your App](https://docs.ergonode.com/apps2/manifest#url).

It contains two important pieces of information:

* `X-APP-TOKEN` HTTP header
* shared secret in the request body

```
{
  "shared_secret": "your_app_installation_shared_secret"
}
```

This secret should be persisted, i.e. the database of choice, and kept by your App safe with information about the app installation it belongs to and the Ergonode API URL retrieved from claims:

* app\_installation\_id
* api\_url

All the following requests by Ergonode to an App should be authenticated using this secret.

You should also encrypt the shared secret within the persistent storage so it is not easily retrievable.

The response status has to be 2xx to process installation appropriately.

## Authentication of the incoming request

Steps to verify whether the request is coming for a specific App installation from Ergonode

1. obtain the token from `X-APP-TOKEN` HTTP header of the request
2. extract the `app_installation_id` claim from the JWT without signature verification
3. retrieve shared secret persisted on the handshake
4. verify JWTs signature using HMAC SHA-256 algorithm and the shared secret

## Authenticate the request to Ergonode

Steps to create an appropriate token authenticating in Ergonode API

1. establish the App installation ID
2. create claims - at the very minimum the following claims are required: `app_installation_id`, `nbf`(not before), `iat`(issued at), `exp`(expiration time)
3. retrieve, persisted on the handshake, shared secret
4. create  JWT with signature signed with HMAC SHA-256 algorithm and the shared secret
5. send the token as `X-APP-TOKEN` HTTP header to Ergonode API URL from handshake

Alternatively, on the requests from the Ergonode, i.e. in synchronization context, you can reuse the token provided by the Ergonode.
