Using the verifySession middleware
Verifying a session using the verifySession
middleware
CAUTION
This guide only applies to scenarios which involve SuperTokens Session Access Tokens.
If you are implementing either, Unified Login or Microservice Authentication, features that make use of OAuth2 Access Tokens, please check the separate page that shows you how to verify those types of tokens.
For your APIs that require a user to be logged in, use the verifySession
middleware:
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(), (req: SessionRequest, res) => {
let userId = req.session!.getUserId();
//....
});
The session
object
This object exposes the following functions:
getHandle
: Returns thesessionHandle
for this session. This is a constant, unique string per session that never changes for its session.getUserId
: Returns the userId of logged in user.getRecipeUserId
: Returns theRecipeUserId
object for the session. If there is only one login method for this user, then thegetRecipeUserId().getAsString()
will be equal to thegetUserId()
. Otherwise, this will point to the user ID of the specific login method for this user.getSessionDataFromDatabase
: Returns the session data (stored in the database) that is associated with the session.updateSessionDataInDatabase
: Set a new JSON object to the session data (stored in the database)getAccessTokenPayload
: Returns the access token's payload for this session. This includes claims defined by you (e.g.: increateNewSession
), standard claims (sub
,iat
,exp
) and supertokens specific ones (sessionHandle
,parentRefreshTokenHash1
, etc.)mergeIntoAccessTokenPayload
: Adds key / values into a JSON object in the access token. Set a key tonull
to remove it from the payload.revokeSession
: Destroys this session in the db and on the frontendgetTimeCreated
: Returns the time in milliseconds of when this session was createdgetExpiry
: Returns the time in milliseconds of when this session will expire if not refreshed.getAccessToken
: Returns the rawstring
access tokengetAllSessionTokensDangerously
: Returns an object that contains the raw string representation of all tokens associated with the session along with a boolean that indicates if thee session needs to be updated on the frontend.getTenantId
: Returns the tenant ID of the session. If you are not using the multi tenancy feature, the value of this will be"public"
, which is the default tenant ID.
getSessionDataFromDatabase
vs getAccessTokenPayload
getSessionDataFromDatabase
queries the SuperTokens Core to get the information, mapped to that session's handle, from the database. WhereasgetAccessTokenPayload
reads directly from the access token used in the request.getSessionDataFromDatabase
is much slower since it requires a network call.- The information stored using
updateSessionDataInDatabase
(changes the result ofgetSessionDataFromDatabase
function call), is not exposed to the frontend in any way. So if you want to store something sensitive against the session handle, use this method. - If you want access to some information in most / all API, like the user's role, then use
getAccessTokenPayload
andmergeIntoAccessTokenPayload
since fetching this information from the session will be very fast (no network call required).
Optional session verification
Sometimes, you want an API to be accessible even if there is no session. In that case, you can use the sessionRequired
flag:
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({sessionRequired: false}),
(req: SessionRequest, res) => {
if (req.session !== undefined) {
let userId = req.session.getUserId();
} else {
// user is not logged in...
}
}
);
Verifying the claims of a session
Sometimes, you may also want to check if there are certain claims in the session as part of the verification process. For example, you may want to check that the session has the admin
role claim for certain APIs, or that the user has completed 2FA.
This can be done using our session claims validator feature. Let's take an example of using the user roles claim to check if the session has the admin claim:
import { verifySession } from "supertokens-node/recipe/session/framework/express";
import express from "express";
import { SessionRequest } from "supertokens-node/framework/express";
import UserRoles from "supertokens-node/recipe/userroles";
let app = express();
app.post(
"/update-blog",
verifySession({
overrideGlobalClaimValidators: async (globalValidators) => [
...globalValidators,
UserRoles.UserRoleClaim.validators.includes("admin"),
// UserRoles.PermissionClaim.validators.includes("edit")
],
}),
async (req: SessionRequest, res) => {
// All validator checks have passed and the user is an admin.
}
);
- We add the
UserRoleClaim
validator to theverifySession
function which makes sure that the user has anadmin
role. - The
globalValidators
represents other validators that apply to all API routes by default. This may include a validator that enforces that the user's email is verified (if enabled by you). - We can also add a
PermissionClaim
validator to enforce a permission.
You can also build your own custom claim validators based on your app's requirements.