reactjs - Automatic login without prompting to the login page after log out in next-auth oauth - Stack Overflow

I'm implementing a LinkedIn sign-in feature in a Next.js 14.2.6 application using Next-Auth v4.24.

I'm implementing a LinkedIn sign-in feature in a Next.js 14.2.6 application using Next-Auth v4.24.11. The initial sign-in works as expected, but after logging out and attempting to sign in again, the user is automatically logged in without being prompted for their email and password. This behavior is not desired, as I want users to re-enter their credentials each time they sign in.

// src/app/api/auth/[...nextauth]/route.ts

import NextAuth from "next-auth";
import { LinkedInProvider } from "next-auth/providers/linkedin";

const handler = NextAuth({
  providers: [
    LinkedInProvider({
      clientId: process.env.LINKEDIN_CLIENT_ID || "",
      clientSecret: process.env.LINKEDIN_CLIENT_SECRET || "",
      client: { token_endpoint_auth_method: "client_secret_post" },
      issuer: ";,
      profile: (profile: LinkedInProfile) => ({
        id: profile.sub,
        name: profile.name,
        email: profile.email,
        image: profile.picture,
      }),
      wellKnown: "/.well-known/openid-configuration",
      authorization: {
        params: {
          scope: "openid profile email",
        },
      },
    }),
  ],
  callbacks: {
    async jwt({ token, account, profile }) {
      if (account) {
        token.accessToken = account.access_token;
      }
      if (profile) {
        token.id = profile.sub;
      }
      return token;
    },
    async session({ session, token }) {
      session.accessToken = token.accessToken as string;
      session.user.id = token.id as string;
      return session;
    },
  },
});

export { handler as GET, handler as POST };

The below code is my logout button

 const handleLogout = async () => {
    try {
      Cookies.remove("next-auth.session-token");
      Cookies.remove("next-auth.csrf-token");
      Cookies.remove("next-auth.callback-url");
      
      await signOut({ redirect: false });
  
      Cookies.remove("isLogged");
      Cookies.remove("userId");
      localStorage.removeItem("profile_pic");
      sessionStorage.clear();
  
      router.push("/login");
    } catch (error) {
      console.error("Error during logout:", error);
    }
  };

Sign In button

<button
    className="linkedin-button flex items-center justify-center w-full py-2 bg-white border rounded-full shadow-md hover:bg-gray-100"
    onClick={() => signIn("linkedin")}
  >
    <Image
      src="/linkedin.webp"
      alt="Logo"
      width={28}
      height={28}
      priority
      className="mr-2"
    />
    Login with LinkedIn
  </button>

It seems the session isn't clearing properly upon sign-out. Although the sign-out response shows session {}, the cookies next-auth.csrf-token and next-auth.callback-url remain. The set-cookie header for sign-out is:

set-cookie: next-auth.callback-url=http%3A%2F%2Flocalhost%3A3000%2Fdashboard%3Fmessage%3Dsuccess; Path=/; HttpOnly; SameSite=Lax

How can I fix this to ensure cookies are cleared correctly?Or Is it bug in the next-auth/feature?

What i have tried so far?

signOut({ redirect: false, callbackUrl: '/' });

Also added prompt:login to the sign in button.

I'm implementing a LinkedIn sign-in feature in a Next.js 14.2.6 application using Next-Auth v4.24.11. The initial sign-in works as expected, but after logging out and attempting to sign in again, the user is automatically logged in without being prompted for their email and password. This behavior is not desired, as I want users to re-enter their credentials each time they sign in.

// src/app/api/auth/[...nextauth]/route.ts

import NextAuth from "next-auth";
import { LinkedInProvider } from "next-auth/providers/linkedin";

const handler = NextAuth({
  providers: [
    LinkedInProvider({
      clientId: process.env.LINKEDIN_CLIENT_ID || "",
      clientSecret: process.env.LINKEDIN_CLIENT_SECRET || "",
      client: { token_endpoint_auth_method: "client_secret_post" },
      issuer: "https://www.linkedin",
      profile: (profile: LinkedInProfile) => ({
        id: profile.sub,
        name: profile.name,
        email: profile.email,
        image: profile.picture,
      }),
      wellKnown: "https://www.linkedin/oauth/.well-known/openid-configuration",
      authorization: {
        params: {
          scope: "openid profile email",
        },
      },
    }),
  ],
  callbacks: {
    async jwt({ token, account, profile }) {
      if (account) {
        token.accessToken = account.access_token;
      }
      if (profile) {
        token.id = profile.sub;
      }
      return token;
    },
    async session({ session, token }) {
      session.accessToken = token.accessToken as string;
      session.user.id = token.id as string;
      return session;
    },
  },
});

export { handler as GET, handler as POST };

The below code is my logout button

 const handleLogout = async () => {
    try {
      Cookies.remove("next-auth.session-token");
      Cookies.remove("next-auth.csrf-token");
      Cookies.remove("next-auth.callback-url");
      
      await signOut({ redirect: false });
  
      Cookies.remove("isLogged");
      Cookies.remove("userId");
      localStorage.removeItem("profile_pic");
      sessionStorage.clear();
  
      router.push("/login");
    } catch (error) {
      console.error("Error during logout:", error);
    }
  };

Sign In button

<button
    className="linkedin-button flex items-center justify-center w-full py-2 bg-white border rounded-full shadow-md hover:bg-gray-100"
    onClick={() => signIn("linkedin")}
  >
    <Image
      src="/linkedin.webp"
      alt="Logo"
      width={28}
      height={28}
      priority
      className="mr-2"
    />
    Login with LinkedIn
  </button>

It seems the session isn't clearing properly upon sign-out. Although the sign-out response shows session {}, the cookies next-auth.csrf-token and next-auth.callback-url remain. The set-cookie header for sign-out is:

set-cookie: next-auth.callback-url=http%3A%2F%2Flocalhost%3A3000%2Fdashboard%3Fmessage%3Dsuccess; Path=/; HttpOnly; SameSite=Lax

How can I fix this to ensure cookies are cleared correctly?Or Is it bug in the next-auth/feature?

What i have tried so far?

signOut({ redirect: false, callbackUrl: '/' });

Also added prompt:login to the sign in button.

Share asked Mar 7 at 12:22 JISHNU T RAJJISHNU T RAJ 181 silver badge6 bronze badges 2
  • This is rather a feature of OAuth itself. If you invoke the login for a user that has already granted the requested permissions previously, and they are still logged in to the OAuth provider's site - then they are not supposed to be bothered with entering any credentials again. Some OAuth providers offer ways to explicitly log out of the provider itself as well, or to "force" a login into the provider's site again, but whether LinkedIn is one of them, I couldn't tell you. – C3roe Commented Mar 7 at 12:36
  • Can i disable that feature? – JISHNU T RAJ Commented Mar 7 at 14:40
Add a comment  | 

1 Answer 1

Reset to default 0

I managed to fix the issue by updating the logout API route and the logout button handler. Below are the updated code snippets that worked for me. API Route (api/auth/logout/route.js)

import { NextResponse } from "next/server";

export async function POST(_req: Request) {
  const response = NextResponse.json({
    success: true,
    logoutUrl: "https://www.linkedin/m/logout/"
  });

  // Clear all auth-related cookies
  const cookiesToClear = [
    "next-auth.session-token",
    "next-auth.callback-url",
    "next-auth.csrf-token",
    "user_session",
    "__Secure-next-auth.session-token",
    "__Host-next-auth.csrf-token"
  ];

  cookiesToClear.forEach(cookieName => {
    response.cookies.set(cookieName, "", {
      path: "/",
      httpOnly: true,
      sameSite: "lax",
      maxAge: 0,
      expires: new Date(0),
    });
  });

  return response;
}

Logout Button

const handleLogout = async () => {
  try {
    Cookies.remove("isLogged");
    Cookies.remove("userId");
    localStorage.removeItem("profile_pic");

    const response = await fetch('/api/auth/logout', { method: 'POST' });
    const data = await response.json();

    if (data.logoutUrl) {
      const logoutWindow = window.open(data.logoutUrl, "_blank");

      setTimeout(() => {
        if (logoutWindow) logoutWindow.close();
        window.location.href = '/login';
      }, 2000);//be sure add 2 seconds else not work properly.
    } else {
      window.location.href = '/login';
    }
  } catch (error) {
    console.error('Logout error:', error);
    window.location.href = '/login';
  }
};

Authorization configuration as follows:

params: {
  scope: "openid profile email",
  prompt: 'login',
  max_age: 0
},

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744930147a4601686.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信