admin管理员组

文章数量:1202599

I have a middleware component, to intercept an OTP on the URL and set an auth cookie so users are not redirected to the login page.

/**
 * Intercept every request and auth OTP if required
 */
export async function middleware(request: NextRequest) {

    const url = request.nextUrl.clone()
    const otp = url.searchParams.get('otp')

    console.log("middleware request: " + url);

    // if there is an OTP and no auth authorise
    if (otp) {
        console.log("middleware, authenticating with OTP: " + otp);
        url.searchParams.delete('otp')
        const response = NextResponse.redirect(url)
        const cookieStore = await cookies();
        const auth = cookieStore.get("auth");
        if (auth === undefined) {
            const API_URL = nextConfig?.env?.API_URL as string;
            const {data} = await axios.post(`${API_URL}/otp`, {otp});
            if (data) {
                const authJson = JSON.stringify(data);
                console.log("middleware, setting auth cookie from OTP: " + authJson)
                response.cookies.set("auth", authJson, {expires: 30, /* 30 days */ path: "/"});
            }
            return response;
        }
    } else {
        const cookieStore = await cookies();
        const auth = cookieStore.get("auth");
        console.log("middleware, auth=true", auth);
    }

    return NextResponse.next()
}

The log looks like this. Why is the cookie not present on the 2nd redirect when the OTP is removed from the URL?

middleware request: http://localhost:3000/boardruns/edit/1?otp=1234
middleware, authenticating with OTP: 1234
middleware, setting auth cookie from OTP: {"name":"name name","email":"[email protected]","roles":["ROLE_USER"],"jwt":"eyJhbG.....hJxVLc"}
middleware request: http://localhost:3000/boardruns/edit/1
middleware, auth=true undefined

I have a middleware component, to intercept an OTP on the URL and set an auth cookie so users are not redirected to the login page.

/**
 * Intercept every request and auth OTP if required
 */
export async function middleware(request: NextRequest) {

    const url = request.nextUrl.clone()
    const otp = url.searchParams.get('otp')

    console.log("middleware request: " + url);

    // if there is an OTP and no auth authorise
    if (otp) {
        console.log("middleware, authenticating with OTP: " + otp);
        url.searchParams.delete('otp')
        const response = NextResponse.redirect(url)
        const cookieStore = await cookies();
        const auth = cookieStore.get("auth");
        if (auth === undefined) {
            const API_URL = nextConfig?.env?.API_URL as string;
            const {data} = await axios.post(`${API_URL}/otp`, {otp});
            if (data) {
                const authJson = JSON.stringify(data);
                console.log("middleware, setting auth cookie from OTP: " + authJson)
                response.cookies.set("auth", authJson, {expires: 30, /* 30 days */ path: "/"});
            }
            return response;
        }
    } else {
        const cookieStore = await cookies();
        const auth = cookieStore.get("auth");
        console.log("middleware, auth=true", auth);
    }

    return NextResponse.next()
}

The log looks like this. Why is the cookie not present on the 2nd redirect when the OTP is removed from the URL?

middleware request: http://localhost:3000/boardruns/edit/1?otp=1234
middleware, authenticating with OTP: 1234
middleware, setting auth cookie from OTP: {"name":"name name","email":"[email protected]","roles":["ROLE_USER"],"jwt":"eyJhbG.....hJxVLc"}
middleware request: http://localhost:3000/boardruns/edit/1
middleware, auth=true undefined
Share Improve this question asked Jan 21 at 6:38 Essex BoyEssex Boy 7,9502 gold badges22 silver badges26 bronze badges 1
  • This question is similar to: Next 14: how to set cookie in middleware and get it in root layout. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. – DarkBee Commented Jan 21 at 6:45
Add a comment  | 

1 Answer 1

Reset to default 0

In case this helps someone else, this is how I solved it.

I added a JWT to the URL of the the client side edit page (at this stage I'm un-authenictaed). On that page I generate the auth. Since I generated the URL I know it's valid, all server side checks of the JWT are the same. A bit of a hack!!

const {params} = useParsed();
const jwt = params?.jwt;
if (jwt) {
    console.log("BoardRunEdit authenticating on the fly");
    Cookies.remove("auth");
    const authData: any = {
        "name": "boardrunner",
        "email": "[email protected]",
        "roles": ['ROLE_USER'],
        "jwt": jwt
    };
    Cookies.set("auth", JSON.stringify(authData), {expires: 30, /* 30 days */ path: "/",});
}

本文标签: reactjsCookie set in midddleware does not workNext JSStack Overflow