Which UI do you use?
Custom UI
Pre built UI
Fetching the access token string
#
On the backend- 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.getAccessToken();
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!.getAccessToken();
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.getAccessToken();
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!.getAccessToken();
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!.getAccessToken();
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!.getAccessToken();
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!.getAccessToken();
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 }> {
// For more information about "AuthGuard" and the "Session" decorator please read our NestJS guide.
const jwt = session.getAccessToken();
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())
jwt := sessionContainer.GetAccessToken()
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()
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()
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()
print(current_jwt) # TODO...
#
On the frontendexposeAccessTokenToFrontendInCookieBasedAuth
#
1) Enable When using cookie based auth, by default, the access token is not readable by the JS on the frontend (since it's stored as httpOnly
cookie). To enable this, you need to set the exposeAccessTokenToFrontendInCookieBasedAuth
config to true
(as shown below
important
If you are only using header-based sessions, you can skip this step
- NodeJS
- GoLang
- Python
import SuperTokens from "supertokens-node";
import Session from "supertokens-node/recipe/session";
SuperTokens.init({
supertokens: {
connectionURI: "..."
},
appInfo: {
apiDomain: "...",
appName: "...",
websiteDomain: "..."
},
recipeList: [
Session.init({
exposeAccessTokenToFrontendInCookieBasedAuth: true,
})
]
});
import (
"github.com/supertokens/supertokens-golang/recipe/session"
"github.com/supertokens/supertokens-golang/recipe/session/sessmodels"
"github.com/supertokens/supertokens-golang/supertokens"
)
func main() {
supertokens.Init(supertokens.TypeInput{
RecipeList: []supertokens.Recipe{
session.Init(&sessmodels.TypeInput{
ExposeAccessTokenToFrontendInCookieBasedAuth: true,
}),
},
})
}
from supertokens_python import init, InputAppInfo
from supertokens_python.recipe import session
init(
app_info=InputAppInfo(
api_domain="...", app_name="...", website_domain="..."),
framework='...',
recipe_list=[
session.init(
expose_access_token_to_frontend_in_cookie_based_auth=True
)
]
)
#
2) Read the access token on the frontend- ReactJS
- Angular
- Vue
import Session from 'supertokens-auth-react/recipe/session';
async function getJWT() {
if (await Session.doesSessionExist()) {
let userId = await Session.getUserId();
let jwt = await Session.getAccessToken();
}
}
import Session from 'supertokens-auth-react/recipe/session';
async function getJWT() {
if (await Session.doesSessionExist()) {
let userId = await Session.getUserId();
let jwt = await Session.getAccessToken();
}
}
import Session from 'supertokens-auth-react/recipe/session';
async function getJWT() {
if (await Session.doesSessionExist()) {
let userId = await Session.getUserId();
let jwt = await Session.getAccessToken();
}
}