Which frontend SDK do you use?
supertokens-web-js / mobile
supertokens-auth-react
Fetching the JWT and reading claims
#
Fetching the JWT on the backend#
Method 1) After session verification- NodeJS
- GoLang
- Python
- Express
- Hapi
- Fastify
- Koa
- Loopback
- AWS Lambda / Netlify
- Next.js
- NestJS
import express from "express";
import { verifySession } from "supertokens-node/recipe/session/framework/express";
let app = express();
app.get("/getJWT", verifySession(), async (req, res) => {
let session = req.session;
let jwt = session.getAccessTokenPayload()["jwt"];
res.json({ token: jwt })
});
import Hapi from "@hapi/hapi";
import { verifySession } from "supertokens-node/recipe/session/framework/hapi";
import { SessionRequest } from "supertokens-node/framework/hapi";
let server = Hapi.server({ port: 8000 });
server.route({
path: "/getJWT",
method: "get",
options: {
pre: [
{
method: verifySession()
},
],
},
handler: async (req: SessionRequest, res) => {
let session = req.session;
let jwt = session!.getAccessTokenPayload()["jwt"];
return res.response({ token: jwt }).code(200);
}
})
import Fastify from "fastify";
import { verifySession } from "supertokens-node/recipe/session/framework/fastify";
let fastify = Fastify();
fastify.get("/getJWT", {
preHandler: verifySession(),
}, (req, res) => {
let session = req.session;
let jwt = session.getAccessTokenPayload()["jwt"];
res.send({ token: jwt });
});
import { verifySession } from "supertokens-node/recipe/session/framework/awsLambda";
import { SessionEvent } from "supertokens-node/framework/awsLambda";
async function getJWT(awsEvent: SessionEvent) {
let session = awsEvent.session;
let jwt = session!.getAccessTokenPayload()["jwt"];
return {
body: JSON.stringify({ token: jwt }),
statusCode: 200,
};
};
exports.handler = verifySession(getJWT);
import KoaRouter from "koa-router";
import { verifySession } from "supertokens-node/recipe/session/framework/koa";
import { SessionContext } from "supertokens-node/framework/koa";
let router = new KoaRouter();
router.get("/getJWT", verifySession(), (ctx: SessionContext, next) => {
let session = ctx.session;
let jwt = session!.getAccessTokenPayload()["jwt"];
ctx.body = { token: jwt };
});
import { inject, intercept } from "@loopback/core";
import { RestBindings, get, response } from "@loopback/rest";
import { verifySession } from "supertokens-node/recipe/session/framework/loopback";
import { SessionContext } from "supertokens-node/framework/loopback";
class GetJWT {
constructor(@inject(RestBindings.Http.CONTEXT) private ctx: SessionContext) { }
@get("/getJWT")
@intercept(verifySession())
@response(200)
handler() {
let session = this.ctx.session;
let jwt = session!.getAccessTokenPayload()["jwt"];
return { token: jwt };
}
}
import { superTokensNextWrapper } from 'supertokens-node/nextjs'
import { verifySession } from "supertokens-node/recipe/session/framework/express";
import { SessionRequest } from "supertokens-node/framework/express";
export default async function getJWT(req: SessionRequest, res: any) {
await superTokensNextWrapper(
async (next) => {
await verifySession()(req, res, next);
},
req,
res
)
let session = req.session;
let jwt = session!.getAccessTokenPayload()["jwt"];
res.json({ token: jwt })
}
import { Controller, Get, UseGuards, Session } from "@nestjs/common";
import { SessionContainer } from "supertokens-node/recipe/session";
import { AuthGuard } from './auth/auth.guard';
@Controller()
export class ExampleController {
@Get('example')
@UseGuards(new AuthGuard())
async postExample(@Session() session: SessionContainer): Promise<{ token: any }> {
const currAccessTokenPayload = session.getAccessTokenPayload();
// For more information about "AuthGuard" and the "Session" decorator please read our NestJS guide.
let jwt = session.getAccessTokenPayload()["jwt"];
return { token: jwt };
}
}
import (
"fmt"
"net/http"
"github.com/supertokens/supertokens-golang/recipe/session"
)
// We assume that you have wrapped this handler with session.VerifySession
func getJWT(w http.ResponseWriter, r *http.Request) {
// retrieve the session object as shown below
sessionContainer := session.GetSessionFromRequestContext(r.Context())
currAccessTokenPayload := sessionContainer.GetAccessTokenPayload()
jwt := currAccessTokenPayload["jwt"]
fmt.Println(jwt)
}
- FastAPI
- Flask
- Django
from supertokens_python.recipe.session.framework.fastapi import verify_session
from fastapi import Depends
from supertokens_python.recipe.session import SessionContainer
@app.get('/getJWT')
async def get_jwt(session: SessionContainer = Depends(verify_session())):
current_jwt = session.get_access_token_payload()['jwt']
print(current_jwt) # TODO...
from supertokens_python.recipe.session.framework.flask import verify_session
from supertokens_python.recipe.session import SessionContainer
from flask import g
@app.route('/getJWT', methods=['GET'])
@verify_session()
def get_jwt():
session: SessionContainer = g.supertokens
current_jwt = session.get_access_token_payload()['jwt']
print(current_jwt) # TODO...
from supertokens_python.recipe.session.framework.django.asyncio import verify_session
from django.http import HttpRequest
from supertokens_python.recipe.session import SessionContainer
@verify_session()
async def get_jwt(request: HttpRequest):
session: SessionContainer = request.supertokens
current_jwt = session.get_access_token_payload()['jwt']
print(current_jwt) # TODO...
#
Method 2) Without session verification- NodeJS
- GoLang
- Python
import Session from "supertokens-node/recipe/session";
async function getJWT() {
let userId = "...";
// we first get all the sessionHandles (string[]) for a user
let sessionHandles = await Session.getAllSessionHandlesForUser(userId);
sessionHandles.forEach(async (handle) => {
let currSessionInfo = await Session.getSessionInformation(handle)
if (currSessionInfo === undefined) {
return;
}
let currentJWT = currSessionInfo.accessTokenPayload["jwt"];
})
}
import (
"fmt"
"github.com/supertokens/supertokens-golang/recipe/session"
)
func main() {
// we first get all the sessionHandles (string[]) for a user
sessionHandles, err := session.GetAllSessionHandlesForUser("userId")
if err != nil {
// TODO: handle error
return
}
// we update all the session's access token payloads for this user
for _, handle := range sessionHandles {
sessionInfo, err := session.GetSessionInformation(handle)
if err != nil {
// TODO: handle error
return
}
currJWT := sessionInfo.AccessTokenPayload["jwt"]
fmt.Println(currJWT)
}
}
- Asyncio
- Syncio
from supertokens_python.recipe.session.asyncio import get_all_session_handles_for_user, get_session_information
async def some_func():
# we first get all the session_handles (List[string]) for a user
session_handles = await get_all_session_handles_for_user("userId")
for handle in session_handles:
session_information = await get_session_information(handle)
if session_information is None:
continue
current_access_token_payload = session_information.access_token_payload
current_jwt = current_access_token_payload['jwt']
print(current_jwt) # TODO..
from supertokens_python.recipe.session.syncio import get_all_session_handles_for_user, get_session_information
# we first get all the session_handles (List[string]) for a user
session_handles = get_all_session_handles_for_user("userId")
for handle in session_handles:
session_information = get_session_information(handle)
if session_information is None:
continue
current_access_token_payload = session_information.access_token_payload
current_jwt = current_access_token_payload['jwt']
#
Fetching the JWT on the frontend- ReactJS
- Angular
- Vue
import Session from 'supertokens-web-js/recipe/session';
async function getJWT() {
if (await Session.doesSessionExist()) {
let userId = await Session.getUserId();
let jwt = (await Session.getAccessTokenPayloadSecurely()).jwt;
}
}
import Session from 'supertokens-auth-react/recipe/session';
async function getJWT() {
if (await Session.doesSessionExist()) {
let userId = await Session.getUserId();
let jwt = (await Session.getAccessTokenPayloadSecurely()).jwt;
}
}
We do not use the useSessionContext
React hook here because reading the JWT from that hook doesn't cause an auto-refresh in case the JWT has expired. Instead, calling await Session.getAccessTokenPayloadSecurely()
does do an auto refresh making sure that the returned JWT is not expired. Therefore, you want to call the Session.getAccessTokenPayloadSecurely()
function as close to the network call as possible.
import Session from 'supertokens-web-js/recipe/session';
async function getJWT() {
if (await Session.doesSessionExist()) {
let userId = await Session.getUserId();
let jwt = (await Session.getAccessTokenPayloadSecurely()).jwt;
}
}
#
Reading the JWT claimsThe JWT claims can be read in two ways:
- Fetch the JWT first (as shown above), verify it and then decode it to get the claims. This can be done using any standard JWT library.; OR
- Just read the properties of the access token payload (as shown above). This works because when you set claims, those are copied over in the SuperTokens' access token as well as in the issued JWT.