Skip to main content

Protecting API routes

caution
  • SuperTokens is not yet optimised for 2FA implementation, so you have to add a lot of customisations for it to work. We are working on improving the development experience for 2FA as well as adding more factors like TOTP. Stay tuned.
  • A demo app that uses the pre built UI can be found on our GitHub.

In the previous steps, we saw the a session is created after the first factor, with SecondFactorClaim set to false, and then after the second factor is completed, we update that value to true.

Protecting all APIs#

We want to protect all the application APIs such that they are accessible only when SecondFactorClaim is true - indicating that the user has completed 2FA. We can do this by by overriding the getGlobalClaimValidators function in the Session recipe.

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

Session.init({
override: {
functions: (oI) => {
return {
...oI,
getGlobalClaimValidators: (input) => [
...input.claimValidatorsAddedByOtherRecipes,
SecondFactorClaim.validators.hasValue(true),
],
};
},
}
})

Protecting specific API routes#

If instead, you want to enforce 2FA just on certain API routes, you can add the validator only when calling the verifySession function:

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("/like-comment", verifySession({
overrideGlobalClaimValidators: (globalValidators) => [
...globalValidators,
SecondFactorClaim.validators.hasValue(true),
]
}), (req: SessionRequest, res) => {
//....
});
important

If the SecondFactorClaim claim validator fails, then the SDK will send a 403 response.

Looking for older version of the documentation?
Which UI do you use?
Custom UI
Pre built UI