Get the Hanko API URL

Retrieve the API URL from the Hanko console.

If you are self-hosting Hanko you need to provide your own URL.

Hanko Authentication with JWT

Upon a successful login, Hanko sends a cookie containing a JSON Web Token (JWT). You can use this JWT to authenticate requests on your backend.

Steps to Authenticate Requests

  1. Retrieve the JSON Web Key Set (JWKS): The JWKS has the public keys to verify the JWT. Fetch it from the Hanko API’s .well-known/jwks.json endpoint.

  2. Verify the JWT: Use the JWKS to verify the JWT.

Go-based Backend Example

Below is a sample middleware for a Go-based backend using the Echo framework and the lestrrat-go/jwx package:

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"github.com/labstack/echo/v4"
	"github.com/lestrrat-go/jwx/v2/jwk"
	"github.com/lestrrat-go/jwx/v2/jwt"
)

func SessionMiddleware() echo.MiddlewareFunc {
  return func(next echo.HandlerFunc) echo.HandlerFunc {
    return func(c echo.Context) error {
      cookie, err := c.Cookie("hanko")
      if err == http.ErrNoCookie {
        return c.Redirect(http.StatusTemporaryRedirect, "/unauthorized")
      }
      if err != nil {
        return err
      }
      // replace "hankoApiURL" with your API URL
      set, err := jwk.Fetch(
        context.Background(),
        fmt.Sprintf("%v/.well-known/jwks.json", hankoApiURL)
      )
      if err != nil {
        return err
      }

      token, err := jwt.Parse([]byte(cookie.Value), jwt.WithKeySet(set))
      if err != nil {
        return c.Redirect(http.StatusTemporaryRedirect, "/unauthorized")
      }

      log.Printf("session for user '%s' verified successfully", token.Subject())

      c.Set("token", cookie.Value)
      c.Set("user", token.Subject())

      return next(c)
    }
  }
}