Obtain your Hanko API URL

  1. Log in to Hanko Cloud and select your project.
  2. Navigate to the Dashboard.
  3. Find your API URL on the top of the dashboard.
  4. Copy the URL to a .env file.
    .env
    HANKO_API_URL=https://f4****-4802-49ad-8e0b-3d3****ab32.hanko.io
    

Validate a session token

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.

See here for more details on sessions

The steps required to validate a session JWT depend on whether sessions are configured to be stateful (server-side) or stateless.

  1. Validate the session using the sessions/validate endpoint: Use the session token to retrieve info about session validity, expiry, and user ID of the user the session is associated with.

Examples

Express

In the following example, we demonstrate how to implement a custom middleware in an Express.js application.

const express = require("express");
const cookieParser = require("cookie-parser");
const dotenv = require("dotenv").config();

const app = new Express();
app.use(cookieParser());

async function validateToken(req, res, next) {
  let token = null;
  if (
    req.headers.authorization &&
    req.headers.authorization.split(" ")[0] === "Bearer"
  ) {
    token = req.headers.authorization.split(" ")[1];
  } else if (req.cookies && req.cookies.hanko) {
    token = req.cookies.hanko;
  }
  if (token === null || token.length === 0) {
    res.status(401).send("Unauthorized");
    return;
  }

  try {
    response = await fetch(`${process.env.HANKO_API_URL}/sessions/validate`, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      method: "POST",
      body: JSON.stringify({
        session_token: token
      })
    });

    if (!response.ok) {
      let error = await response.json();
      sendError(res, error);
      return;
    }

    const session = await response.json()

    if (!session.is_valid) {
      sendError(res, error);
      return;
    }

  } catch (error) {
    sendError(res, error)
    return;
  }

  next();
}

function sendError(res, cause) {
  let error = { message: "Invalid session token" }

  if (cause) {
    error.cause = cause;
  }

  res.status(401).send(error)
}

app.use(validateToken);

app.get("/protected", function (req, res) {
  res.sendStatus(200);
});

Try it yourself

Node and Express.js example (React frontend)

Full source code available on our GitHub.

Node and Express.js example (Vue frontend)

Full source code available on our GitHub.

Node and Express.js example (Svelte frontend)

Full source code available on our GitHub.