> ## Documentation Index
> Fetch the complete documentation index at: https://docs.abbyy.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication using JSON Web Tokens

> Authenticate ABBYY FlexiCapture 12 users with JSON Web Tokens: create a signed JWT, POST it to the Application Server, and use the returned ticket in calls.

## Overview of the authentication process

JSON Web Token (JWT) is a data transfer format that is used to transfer data securely between the ABBYY FlexiCapture 12 Application Server and third-party services. When authenticating through JWT, no identification data is sent to the Application Server. Authentication is carried out on a third-party service, following which the Application Server is informed that the user has been authenticated by a trusted service.

## Implementation

### Get JSON data

JSON data sample:

```json theme={null}
{"alg":"RS256","kid":"-JLCtyyTyF69AZrtjpk-xGs-nUE","x5t":"-JLCtyyTyF69AZrtjpk-xGs-nUE","typ":"JWT"}
{"nameid":"user","nbf":1572267172,"exp":1572267772,"iss":"ABBYY","aud":"test JWT app"}
```

JSON data containing user certificates is encrypted in Base64 to create a JSON web token (JWT).

The following sample creates a JWT token:

```csharp theme={null}
using System.IdentityModel.Tokens.Jwt;
using System.Security.Cryptography.X509Certificates;
…

static string createEncryptedJwtToken(
    X509Certificate2 encryptCert,
    string issuer,
    string audience,
    string nameid,
    TimeSpan expirationTimespan )
{
    X509SigningCredentials signingCredentials = new X509SigningCredentials( encryptCert );
    JwtHeader jwtHeader = new JwtHeader( signingCredentials );
    var claims = new Claim[]
    {
        new Claim( "nameid", nameid )
    };
    var now = DateTime.UtcNow;
    JwtSecurityToken newToken = new JwtSecurityToken(
        issuer,
        audience,
        claims,
        now,
        now.Add( expirationTimespan ),
        signingCredentials
    );
    var token = new JwtSecurityTokenHandler().WriteToken(newToken);
    return token;
}
```

### Send a JWT to the Application Server

A JWT needs to be sent to the Application Server using the following URL: `https://<ApplicationServer>/Flexicapture12/Server/jwt`. This is done using a POST request.

<Note>
  If you are using a tenant, add the tenant's identifier to the Application Server URL: `https://<ApplicationServer>/Flexicapture12/Server/jwt?Tenant=MyTenantName`
</Note>

```csharp theme={null}
static async Task<string> AuthenticateByJwtAsync( string jwtToken )
{
    var fields = new Dictionary<string, string>
    {
        { "JwtToken", jwtToken }
    };
    FormUrlEncodedContent content = new FormUrlEncodedContent( fields );
    using ( var client = new HttpClient() )
    {
        HttpResponseMessage response = await client.PostAsync( jwtServiceUrl, content );
        if ( response.StatusCode == HttpStatusCode.OK )
        {
            return response.Headers.GetValues( "AuthTicket" )?.First() ?? throw new Exception( "AuthTicket header not found" );
        }
        else
        {
            throw new Exception( await response.Content.ReadAsStringAsync() );
        }
    }
}
```

For authentication to work, a user with a login matching the identifier in the JWT (enclosed in the `nameid` node value) must be registered on the Application Server.

The Application Server returns a response like this:

```xml theme={null}
<?xml version="1.0" encoding="utf-8" ?>
<authTicket>
    <userName>user</userName>
    <ticket>79BB391216E9BBA3DA13E5F29669FF1EB48C387C8FDE41D473AA5698A2E16A8B6E91470F05F3C2FBF685630FD7683DC2FA42A900A007CFAD1AD310FEE1ADADFC</ticket>
</authTicket>
```

The value in the `ticket` field is the authenticated ABBYY FlexiCapture 12 ticket. You can use this ticket to make calls to all Application Server interfaces that require authentication. Services should be accessed using ABBYY FlexiCapture authentication, that is, addresses starting with `https://<ApplicationServer>/flexicapture12/Server/FCAuth/` or `https://<ApplicationServer>/flexicapture12/Server/MobileApp/`.

### Use an authenticated ABBYY FlexiCapture 12 ticket

You can pass an authenticated ABBYY FlexiCapture 12 ticket to the server using a cookie file (the file must be named `FlexiCaptureTmpPrn`) or an `Authorization: Bearer` header.

For example:

```
Authorization: Bearer 82BD00C6601EB7F8EF4265450F934D4103C5CA2F010DE1C5FAB4CC830A82300C743D09E5477279733F283D0B6E1C93ACC30FE353D4D9396649965432AAA7994078C3CC63567A95A35E03DA6FDE020F57
```

We recommend using an `Authorization: Bearer` header (cookies are only supported for downward compatibility).

### Set up a trusted certificate on the Application Server

The Application Server will check the data received from the identity provider. For the Application Server to trust this data, it should be signed with a custom certificate issued by an authority from the Application Server database of trusted authorities.

Import the certificate to the ABBYY FlexiCapture database. Now data will be checked using this certificate. For more information, see [Set up Single Sign-On](/flexi-capture/sso-settings).

If the check fails, the Application Server will refer to the `AllowMixedModeCertificateValidation` parameter in the `<appSettings>` settings in the `Web.config` file. If this parameter is set to `true`, the check will be carried out using the certificate added into the **Trusted Root Certification Authorities** folder in the Local Computer certificate store on the computer that is running the Application Server.

If no certificates are added to the database, the check will be carried out using the certificate located in the **Trusted Root Certification Authorities** folder, and the `AllowMixedModeCertificateValidation` parameter will be ignored.

**To download the project and accompanying materials, use this link:** [JWT\_Example.zip](JWT_Example.zip)
