Sihl Token

A token is a string that has some values associated with it. Tokens are often used for authentication by associating a user_id to a string.

Backends

sihl-token ships with 4 backend implementations.

JSON Web Token

JSON Web Token (JWT) is a standard for client-side tokens. The associated data is stored in the actual token, which is signed and sent to the client.

JWTs are valid until they expire. If you want to invalidate them before, it is necessary to keep a blacklist on the server. This requires some persistent storage.

Use either Sihl_token.JwtPostgreSql or Sihl_token.JwtMariaDb.

Server-side

Server-side tokens have their data persisted on the server. This is useful for sensitive information.

Use either Sihl_token.PostgreSql or Sihl_token.MariaDb.

Installation

Backend

First, choose a backend in service/service.ml:

module Token = Sihl_token.JwtPostgresql

Registration

Register the service in run/run.ml:

let services = [ Service.Token.register () ]

Migrations

Run make sihl migrate to run pending migrations.

Usage

The API is documented in Sihl.Contract.Token.Sig.

Middleware

The token middleware Sihl.Contract.Token.Sig.Web.Middleware.user fetches the current user based on the provided Bearer Token.

let index req =

  match Service.Token.Web.User.find_opt req with
  | None -> Lwt.return @@ Sihl.Web.Response.redirect_to "/login"
  | Some user -> Lwt.return @@ Sihl.Web.Response.of_html (View.Welcome.index user)
;;