Revoking a session
#
Online modeThis is applicable when the user is online and you want to revoke their session via an API call from their frontend client.
signOut
function from the frontend#
Method 1: Call the - ReactJS
- Angular
- Vue
The signOut
method revokes the session on the frontend and backend.
import React from "react";import { signOut } from "supertokens-auth-react/recipe/thirdpartypasswordless";
function NavBar() { async function onLogout() { await signOut(); window.location.href = "/"; } return ( <ul> <li>Home</li> <li onClick={onLogout}>Logout</li>
</ul> )}
The signOut
method revokes the session for the user.
import Session from "supertokens-web-js/recipe/session";
async function logout () { await Session.signOut(); window.location.href = "/";}
The signOut
method revokes the session for the user.
import Session from "supertokens-web-js/recipe/session";
async function logout () { await Session.signOut(); window.location.href = "/";}
revokeSession
function post session verification on the backend#
Method 2: Call the - 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";import { SessionRequest } from "supertokens-node/framework/express";
let app = express();
app.post("/someapi", verifySession(), async (req: SessionRequest, res) => {
// This will delete the session from the db and from the frontend (cookies) await req.session!.revokeSession();
res.send("Success! User session revoked");});
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: "/someapi", method: "post", options: { pre: [ { method: verifySession() }, ], }, handler: async (req: SessionRequest, res) => { // This will delete the session from the db and from the frontend (cookies) await req.session!.revokeSession(); return res.response("Success! User session revoked").code(200); }})
import Fastify from "fastify";import { verifySession } from "supertokens-node/recipe/session/framework/fastify";import { SessionRequest } from "supertokens-node/framework/fastify";
let fastify = Fastify();
fastify.post("/someapi", { preHandler: verifySession(),}, async (req: SessionRequest, res) => { // This will delete the session from the db and from the frontend (cookies) await req.session!.revokeSession();
res.send("Success! User session revoked");});
import { verifySession } from "supertokens-node/recipe/session/framework/awsLambda";import { SessionEvent } from "supertokens-node/framework/awsLambda";
async function someapi(awsEvent: SessionEvent) { // This will delete the session from the db and from the frontend (cookies) await awsEvent.session!.revokeSession();
return { body: JSON.stringify({ message: "Success! User session revoked" }), statusCode: 200, };};
exports.handler = verifySession(someapi);
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.post("/someapi", verifySession(), async (ctx: SessionContext, next) => { // This will delete the session from the db and from the frontend (cookies) await ctx.session!.revokeSession();
ctx.body = "Success! User session revoked";});
import { inject, intercept } from "@loopback/core";import { RestBindings, post, response } from "@loopback/rest";import { verifySession } from "supertokens-node/recipe/session/framework/loopback";import { SessionContext } from "supertokens-node/framework/loopback";
class Logout { constructor(@inject(RestBindings.Http.CONTEXT) private ctx: SessionContext) { } @post("/someapi") @intercept(verifySession()) @response(200) async handler() { // This will delete the session from the db and from the frontend (cookies) await this.ctx.session!.revokeSession();
return "Success! User session revoked"; }}
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 someapi(req: SessionRequest, res: any) { await superTokensNextWrapper( async (next) => { await verifySession()(req, res, next); }, req, res ) // This will delete the session from the db and from the frontend (cookies) await req.session!.revokeSession(); res.send("Success! User session revoked");}
import { Controller, Post, UseGuards, Request, Response, Session } from "@nestjs/common";import { SessionContainer } from "supertokens-node/recipe/session";import { AuthGuard } from './auth/auth.guard';
@Controller()export class ExampleController { // For more information about "AuthGuard" and the "Session" decorator please read our NestJS guide. @Post('someapi') @UseGuards(new AuthGuard()) async postSomeAPI(@Session() session: SessionContainer): Promise<string> { await session.revokeSession();
return "Success! User session revoked"; }}
import ( "net/http"
"github.com/supertokens/supertokens-golang/recipe/session" "github.com/supertokens/supertokens-golang/supertokens")
func someAPI(w http.ResponseWriter, r *http.Request) { // retrieve the session object as shown below sessionContainer := session.GetSessionFromRequestContext(r.Context())
// This will delete the session from the db and from the frontend (cookies) err := sessionContainer.RevokeSession() if err != nil { err = supertokens.ErrorHandler(err, r, w) if err != nil { // TODO: Send 500 status code to client } return }
// TODO: Send 200 response to client}
- FastAPI
- Flask
- Django
from supertokens_python.recipe.session.framework.fastapi import verify_sessionfrom supertokens_python.recipe.session import SessionContainerfrom fastapi import Dependsfrom fastapi.responses import PlainTextResponse
async def some_api(session: SessionContainer = Depends(verify_session())): await session.revoke_session() # This will delete the session from the db and from the frontend (cookies) return PlainTextResponse(content='success')
from supertokens_python.recipe.session.framework.flask import verify_sessionfrom supertokens_python.recipe.session import SessionContainerfrom flask import g
@app.route('/some_api', methods=['POST']) @verify_session()def some_api(): session: SessionContainer = g.supertokens
session.sync_revoke_session() # This will delete the session from the db and from the frontend (cookies) return 'success'
from supertokens_python.recipe.session.framework.django.asyncio import verify_sessionfrom django.http import HttpRequestfrom supertokens_python.recipe.session import SessionContainer
@verify_session()async def some_api(request: HttpRequest): session: SessionContainer = request.supertokens This will delete the session from the db and from the frontend (cookies) await session.revoke_session()
#
Offline modecaution
This method of revoking a session will only delete the session from the database and not from the frontend.
This implies that the user will still be able to access protected endpoints while their access token is alive.
If you want to instantly logout the user in this mode, you should enable access token blacklisting.
This is applicable when the user is offline, or if you want to revoke their session from the backend.
sessionHandle
#
Method 1: Revoke a session using its - NodeJS
- GoLang
- Python
import Session from "supertokens-node/recipe/session";
async function revokeSession(sessionHandle: string) { let revoked = await Session.revokeSession(sessionHandle);};
import "github.com/supertokens/supertokens-golang/recipe/session"
func main() { sessionHandle := "someSessionHandle" revoked, err := session.RevokeSession(sessionHandle) if err != nil { // TODO: Handle error return }
if revoked { // session was revoked } else { // session was not found }}
- Asyncio
- Syncio
from supertokens_python.recipe.session.asyncio import revoke_session
async def some_func(): session_handle = "someSessionHandle" _ = await revoke_session(session_handle)
from supertokens_python.recipe.session.syncio import revoke_session
session_handle = "someSessionHandle"revoked = revoke_session(session_handle)
You can fetch all of the sessionHandle
s for a user using the getAllSessionHandlesForUser
function
#
Method 2: Revoke all sessions for a user- NodeJS
- GoLang
- Python
import express from "express";import Session from "supertokens-node/recipe/session";
let app = express();
app.use("/revoke-all-user-sessions", async (req, res) => {
let userId = req.body.userId await Session.revokeAllSessionsForUser(userId);
res.send("Success! All user sessions have been revoked");});
import ( "fmt"
"github.com/supertokens/supertokens-golang/recipe/session")
func main() { revokedSessionHandles, err := session.RevokeAllSessionsForUser("userId") if err != nil { // TODO: Handle error return }
// revokedSessionHandles is an array of revoked session handles. fmt.Println(revokedSessionHandles)}
- Asyncio
- Syncio
from supertokens_python.recipe.session.asyncio import revoke_all_sessions_for_user
async def some_func(): user_id = "someUserId" revoked_session_handles = await revoke_all_sessions_for_user(user_id)
print(revoked_session_handles) # revoked_session_handles is an array of revoked session handles.
from supertokens_python.recipe.session.syncio import revoke_all_sessions_for_user
user_id = "someUserId"revoked_session_handles = revoke_all_sessions_for_user(user_id)
# revoked_session_handles is an array of revoked session handles.