API router can't access cookies when using the production server
Unanswered
Asiatic Lion posted this in #help-forum
Asiatic LionOP
I have a backend in .NET that does authentication with a CAS system and sets a cookie to authenticate clients. My client is a Next.js application.
When running the .NET API locally, everything works as expected. But when hitting the API running on my server, my Next.js route doesn't have access to the cookies. The cookie header in the request from the callback URL is empty.
This is my route:
Any idea what might be happening? I've tried:
- Disabling httpOnly
- Running both the API and next app with https
When running the .NET API locally, everything works as expected. But when hitting the API running on my server, my Next.js route doesn't have access to the cookies. The cookie header in the request from the callback URL is empty.
This is my route:
export async function GET(request) {
const cookieStore = cookies();
if (cookieStore.has("currentUser") && cookieStore.has("perms")) {
return NextResponse.redirect(new URL("/web_app/index", request.url));
}
const cookieName = "DatosPersonalesTH.CAS";
const cookie = cookieStore.get(cookieName)?.value;
if (!cookie) {
console.log("Cookie was not set on callback from CAS");
return NextResponse.redirect(new URL("/login", request.url));
}
const res = await fetch(`${getBaseApiURL()}/users/me`, {
headers: {
Cookie: `${cookieName}=${cookie}`,
},
});
if (res.status === 401) {
console.log("API returned 401 on /users/me after callback from CAS");
return NextResponse.redirect(new URL("/login", request.url));
}
const user = await res.json();
cookieStore.set("currentUser", user.usuario);
if (user.permisos && user.permisos.length > 0) {
cookieStore.set(
"perms",
user.permisos.map((permiso) => {
return permiso.nombre;
}),
);
}
return NextResponse.redirect(new URL("/web_app/index", request.url));
}Any idea what might be happening? I've tried:
- Disabling httpOnly
- Running both the API and next app with https
1 Reply
Asiatic LionOP
For more context, I can see that the cookie is correctly set in the browser because I can hit the authenticated endpoints of the backend API (by typing the url in the browser bar) and see the cookie sent in the request.