Claims validation - SuperTokens Docs

Claims validation

Validate your resources based on claims that get attached to the session.

Overview

SuperTokens provides two approaches for working with authorization data:

  1. Session Claims: An abstraction that includes automatic validation and refresh capabilities
  2. Access Token Payload: A basic way to check the token payload

In most cases, the recommended approach is to use session claims. Use the following table to understand the differences between the two approaches.

Feature Session Claims Access Token Payload
Store simple static data ✅ ✅
Built-in validation ✅ ❌
Automatic refresh mechanism ✅ ❌
Graceful validation failure handling ✅ ❌
Lightweight implementation ❌ ✅
No validation overhead ❌ ✅

This guide shows you how to use each method.

References

Session claim interface

import { RecipeUserId } from "supertokens-node";
import { JSONObject, UserContext } from "supertokens-node/types";

interface SessionClaim<T> {
  readonly key: string;
  fetchValue(
    userId: string,
    recipeUserId: RecipeUserId,
    tenantId: string,
    currentPayload: JSONObject | undefined,
    userContext: UserContext,
  ): Promise<T | undefined> | T | undefined;
  removeFromPayload(payload: JSONObject, userContext: UserContext): JSONObject;
  getValueFromPayload(payload: JSONObject, userContext: UserContext): T | undefined;
}

The SDK provides a few base claim classes which make it easy for you to implement your own claims:

All the recipe claims are built around these primitives:

On the frontend

type SessionClaim<T> = {
  refresh(userContext: any): Promise<void>;
  getValueFromPayload(payload: any, userContext: any): T | undefined;
  getLastFetchedTime(payload: any, userContext: any): number | undefined;
};

When used, these objects provide a way for the SuperTokens SDK to update the claim values when needed. For example, in the built-in email verification claim, the refresh function calls the backend API to check if the email has verification. That API in turn updates the session claim to reflect the email verification status.

Claim Validator

Once you add a claim to the session, specify the checks that need to run on them during session verification. For example, if an API should allow access only to admin roles, there must be a way to tell SuperTokens to do that check.

type SessionClaimValidator = {
  id: string;
  claim: SessionClaim<any>;
  shouldRefetch: (payload: any, userContext: any) => boolean | Promise<boolean>;
  validate: (payload: any, userContext: any) => Promise<ClaimValidationResult>;
};

type ClaimValidationResult = { isValid: true } | { isValid: false; reason?: any };

Conceptually, SuperTokens runs the following session claim validation process during session verification:

function validateSessionClaims(accessToken, claimValidators) {
  payload = accessToken.getPayload();
  failedClaims = [];
  for (validator in claimValidators) {
    validationResult = validator.validate(payload);
    if (!validationResult.isValid) {
      failedClaims.push({ id: validator.id, reason: validationResult.reason });
    }
  }
  return failedClaims;
}

The built-in base claims (PrimitiveClaim, PrimitiveArrayClaim, BooleanClaim) all expose a set of useful validators:

Before you start

Using session claims

SuperTokens sessions have a property called accessTokenPayload. This is a JSON object which you can access on the frontend and backend. The key-values in this JSON payload refer to claims.

1. Create a custom claim

import { BooleanClaim } from "supertokens-node/recipe/session/claims";

const SecondFactorClaim = new BooleanClaim({
  key: "2fa-completed",
  fetchValue: () => false,
});

2. Add claim validators

Backend global validation

import SuperTokens from "supertokens-node";
import Session from "supertokens-node/recipe/session";

SuperTokens.init({
  supertokens: {
    connectionURI: "...",
  },
  appInfo: {
    apiDomain: "...",
    appName: "...",
    websiteDomain: "...",
  },
  recipeList: [
    Session.init({
      override: {
        functions: (originalImplementation) => {
          return {
            ...originalImplementation,
            getGlobalClaimValidators: async function (input) {
              return [...input.claimValidatorsAddedByOtherRecipes, SecondFactorClaim.validators.isTrue()];
            },
          };
        },
      },
    }),
  ],
});

Backend route-specific validation

import express from "express";
import { verifySession } from "supertokens-node/recipe/session/framework/express";
import { UserRoleClaim } from "supertokens-node/recipe/userroles";

let app = express();

app.post(
  "/admin-only",
  verifySession({
    overrideGlobalClaimValidators: async (globalValidators) => [
      ...globalValidators,
      UserRoleClaim.validators.includes("admin"),
    ],
  }),
  async (req, res) => {
    // Only admin users can access this endpoint
  },
);

Frontend validation

import React from "react";
import { SessionAuth } from "supertokens-auth-react/recipe/session";
import { UserRoleClaim } from "supertokens-auth-react/recipe/userroles";

const AdminRoute = (props: React.PropsWithChildren<any>) => {
  return (
    <SessionAuth
      overrideGlobalClaimValidators={(globalValidators) => [
        ...globalValidators,
        UserRoleClaim.validators.includes("admin"),
      ]}
    >
      {props.children}
    </SessionAuth>
  );
};

3. Handle validation failures

Backend custom error handling

import { Error as STError } from "supertokens-node/recipe/session";
import { UserRoleClaim } from "supertokens-node/recipe/userroles";

if (roles === undefined || !roles.includes("admin")) {
  throw new STError({
    type: "INVALID_CLAIMS",
    message: "User is not an admin",
    payload: [
      {
        id: UserRoleClaim.key,
      },
    ],
  });
}

Frontend redirection

import { SessionAuth } from "supertokens-auth-react/recipe/session";
import { UserRoleClaim } from "supertokens-auth-react/recipe/userroles";

const AdminRoute = (props: React.PropsWithChildren<any>) => {
  return (
    <SessionAuth
      overrideGlobalClaimValidators={(globalValidators) => [
        ...globalValidators,
        {
          ...UserRoleClaim.validators.includes("admin"),
          onFailureRedirection: () => "/not-an-admin",
        },
      ]}
    >
      {props.children}
    </SessionAuth>
  );
};

Using the Access Token Payload

The access token payload is a simple way to store custom data that needs to be accessible on both the frontend and the backend.

1. Add Custom Claims to the Access Token Payload

During session creation

import SuperTokens from "supertokens-node";
import Session from "supertokens-node/recipe/session";

SuperTokens.init({
  supertokens: {
    connectionURI: "...",
  },
  appInfo: {
    apiDomain: "...",
    appName: "...",
    websiteDomain: "...",
  },
  recipeList: [
    Session.init({
      override: {
        functions: (originalImplementation) => {
          return {
            ...originalImplementation,
            createNewSession: async function (input) {
              let userId = input.userId;
              input.accessTokenPayload = {
                ...input.accessTokenPayload,
                someKey: "someValue",
              };
              return originalImplementation.createNewSession(input);
            },
          };
        },
      },
    }),
  ],
});

Post Session Creation

import express from "express";
import { verifySession } from "supertokens-node/recipe/session/framework/express";
import { SessionRequest } from "supertokens-node/framework/express";

let app = express();

app.post("/updateinfo", verifySession(), async (req: SessionRequest, res) => {
  let session = req.session;
  await session!.mergeIntoAccessTokenPayload({ newKey: "newValue" });
  res.json({ message: "successfully updated access token payload" });
});

2. Read the Access Token Payload

On the backend

import express from "express";
import { verifySession } from "supertokens-node/recipe/session/framework/express";

let app = express();

app.get("/myApi", verifySession(), async (req, res) => {
  let session = req.session;
  let accessTokenPayload = session.getAccessTokenPayload();
  let customClaimValue = accessTokenPayload.customClaim;
});

On the frontend

import Session from "supertokens-auth-react/recipe/session";

async function someFunc() {
  if (await Session.doesSessionExist()) {
    let accessTokenPayload = await Session.getAccessTokenPayloadSecurely();
    let customClaimValue = accessTokenPayload.customClaim;
  }
}