gpt4 book ai didi

Next-auth session immediately becomes unauthenticated after successful login in a Next.js app(成功登录到Next.js应用程序后,Next-auth会话立即变为未经身份验证)

转载 作者:bug小助手 更新时间:2023-10-25 13:40:09 26 4
gpt4 key购买 nike



I'm using next-auth in my Next.js app for authentication. After successfully logging in, I'm immediately redirected to the login page, indicating that the session has become unauthenticated.

我在我的Next.js应用程序中使用Next-auth进行身份验证。成功登录后,我立即被重定向到登录页面,表明该会话已变为未经身份验证。


Relevant code snippets:

相关代码片段:


_app.tsx:

_app.tsx:


const App = ({
Component,
pageProps: { session, ...pageProps },
emotionCache = clientSideEmotionCache,
}: any) => {
const getLayout = Component.getLayout;
// ... other logic ...

if (session.status === "unauthenticated") {
return <Redirect to="/login" />;
} else {
// Render the main component
}
};

Layout.tsx:

Layout.tsx:


const session = useSession();
const router = useRouter();

if (session.status === "loading") {
return <>loading...</>;
}
if (session.status === "unauthenticated") {
router.push("/login");
}


login.tsx (token callback):

Login.tsx(令牌回调):


async function token(token, user) {
return Promise.resolve({
accessToken: token.accessToken,
refreshToken: token.refreshToken,
accessTokenExpires: token.accessTokenExpires,
user,
});
}


Behavior:

行为:


Upon successful login from the login.tsx component, I'm redirected to a page wrapped with the Layout.tsx component. Almost immediately, the session status becomes unauthenticated, causing the Layout.tsx to redirect back to the /login page.

从login.tsx组件成功登录后,我将被重定向到一个用Layout.tsx组件包装的页面。会话状态几乎立即变为未经身份验证,导致Layout.tsx重定向回/login页面。


I've tried adjusting the token's expiration time (expiresIn) to different values, but the issue persists.
There is no other logic in my app that pushes to the login route after logging in.

我尝试将令牌的到期时间(ExpiresIn)调整为不同的值,但问题仍然存在。在我的应用程序中,没有其他逻辑会在登录后推送到登录路径。


Question:

问题:


What could be causing the session to become unauthenticated immediately after logging in? How can I ensure the session remains authenticated for the user after a successful login?

是什么原因导致会话在登录后立即变得未经身份验证?如何确保会话在成功登录后仍对用户进行身份验证?


更多回答
优秀答案推荐

Seems you are missing the SessionProvider. See https://next-auth.js.org/getting-started/example#configure-shared-session-state

您似乎缺少SessionProvider。请参阅https://next-auth.js.org/getting-started/example#configure-shared-session-state


更多回答

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com