Protecting API routes
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.
1. 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),
],
};
},
}
})
2. 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.