3. Session verification / Building your APIs
When building your own APIs, you may need to verify the session of the user before proceeding further. SuperTokens SDK exposes a verifySession
function that can be utilized for this. In this guide, we will be creating a /user
GET
route that will return the current session information.
/user
GET
route in your API Gateway#
1) Add Create a /user
resource and then GET
method in your API Gateway. Configure the lambda integration and CORS just like we did for the auth routes.
/user
route.#
2) Create a file in your lambda to handle the - NodeJS
- Python
- Other Frameworks
Important
An example of this is here.
import supertokens from "supertokens-node";
import { getBackendConfig } from "./config.mjs";
import { verifySession } from "supertokens-node/recipe/session/framework/awsLambda";
import middy from "@middy/core";
import cors from "@middy/http-cors";
supertokens.init(getBackendConfig());
const lambdaHandler = async (event) => {
return {
body: JSON.stringify({
sessionHandle: event.session.getHandle(),
userId: event.session.getUserId(),
accessTokenPayload: event.session.getAccessTokenPayload(),
}),
statusCode: 200,
};
};
export const handler = middy(verifySession(lambdaHandler))
.use(
cors({
origin: getBackendConfig().appInfo.websiteDomain,
credentials: true,
headers: ["Content-Type", ...supertokens.getAllCORSHeaders()].join(", "),
methods: "OPTIONS,POST,GET,PUT,DELETE",
})
)
.onError((request) => {
throw request.error;
});
Now, import this function in your index.mjs
handler file as shown below:
import supertokens from "supertokens-node";
import { middleware } from "supertokens-node/framework/awsLambda";
import { getBackendConfig } from "./config.mjs";
import middy from "@middy/core";
import cors from "@middy/http-cors";
import { handler as userHandler } from "./user.mjs";
supertokens.init(getBackendConfig());
export const handler = middy(
middleware((event) => {
if (event.path === "/user") {
return userHandler(event);
}
return {
body: JSON.stringify({
msg: "Hello!",
}),
statusCode: 200,
};
})
)
.use(
cors({
origin: getBackendConfig().appInfo.websiteDomain,
credentials: true,
headers: ["Content-Type", ...supertokens.getAllCORSHeaders()].join(", "),
methods: "OPTIONS,POST,GET,PUT,DELETE",
})
)
.onError((request) => {
throw request.error;
});
note
The verifySession
middleware automatically returns a 401 Unauthorised error if the session is not valid. You can alter the default behaviour by passing { sessionRequired: false }
as the second argument to the verifySession
middleware.
import nest_asyncio
nest_asyncio.apply()
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from mangum import Mangum
from supertokens_python import init, get_all_cors_headers
from supertokens_python.framework.fastapi import get_middleware
import config
init(
supertokens_config=config.supertokens_config,
app_info=config.app_info,
framework=config.framework,
recipe_list=config.recipe_list,
mode="asgi",
)
app = FastAPI(title="SuperTokens Example")
from fastapi import Depends
from supertokens_python.recipe.session.framework.fastapi import verify_session
from supertokens_python.recipe.session import SessionContainer
@app.get("/user")
def user(s: SessionContainer = Depends(verify_session())):
return {
"sessionHandle": s.get_handle(),
"userId": s.get_user_id(),
"accessTokenPayload": s.get_access_token_payload()
}
app.add_middleware(get_middleware())
app = CORSMiddleware(
app=app,
allow_origins=[
config.app_info.website_domain
],
allow_credentials=True,
allow_methods=["GET", "PUT", "POST", "DELETE", "OPTIONS", "PATCH"],
allow_headers=["Content-Type"] + get_all_cors_headers(),
)
handler = Mangum(app)
note
The verify_session
middleware automatically returns a 401 Unauthorised error if the session is not valid. You can alter the default behaviour by passing session_required=False
the verify_session
middleware.