security - How to get XSRF-TOKEN on frontend? - Stack Overflow

admin2025-04-21  2

My nextjs application has XSRF-TOKEN that I with my limited knowledge have linked to my FastAPI backend, and GET requests all work. But to send post requests, I am sending them directly from the front end to the backend instead of using the nextjs backend as a middleman (which I am using for the GET requests). The reason being - serverless architecture has a 6MB size limit and I am working with images as the attached files.


import { options } from "@/auth";
import { getServerSession } from "next-auth";
import { parse } from "cookie";
import { NextResponse } from "next/server";
.
.
.
.
.
const session = (await getServerSession(options)) as {
      accessToken: string;
    };
const cookieHeader = request.headers.get("cookie") || "";
const cookies = parse(cookieHeader);
const csrfToken = cookies["XSRF-TOKEN"];

This is what works on the backend of nextjs.

The fastapi setup is as follows:

 async def JWT(self, req: Request = None):
        if not req:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Request not found",
                headers={"WWW-Authenticate": "Bearer"},
            )
        # Proceed with JWT validation using NextAuthJWTv4
        jwt_instance = NextAuthJWTv4(
            secret=config["NEXTAUTH_SECRET"],
            csrf_prevention_enabled=False
        )
        # Assuming NextAuthJWTv4 expects the request or token as input
        try: 
            result = jwt_instance(req)
            if result:
                req.email = result["email"]
                return req
            else:
                raise HTTPException(
                    status_code=status.HTTP_401_UNAUTHORIZED,
                    detail="Not authenticated",
                    headers={"WWW-Authenticate": "Bearer"},
                )
            
        except Exception as e:
            logger.error(e)
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Not authenticated",
                headers={"WWW-Authenticate": "Bearer"},
            )
转载请注明原文地址:http://anycun.com/QandA/1745228034a90492.html