当我在下一个身份验证的提供者中选择凭据时,如何同步下一个身份验证会话的过期时间和来自服务器的令牌
我已经为我的 Next.js 应用程序实现了 next-auth 身份验证系统。在提供程序中,我选择了凭据,因为我有一个 Node.js 后端服务器。
我面临的问题是下一个身份验证会话的过期与我后端的 jwt 令牌的过期不同步。这会导致不一致。请帮助我。
下面是我的下一个授权代码
import NextAuth, {
NextAuthOptions,
Session,
SessionStrategy,
User,
} from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { login } from "@actions/auth";
import { toast } from "react-toastify";
import { JWT } from "next-auth/jwt";
import { NextApiRequest, NextApiResponse } from "next";
import { SessionToken } from "next-auth/core/lib/cookie";
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
const nextAuthOptions = (req: NextApiRequest, res: NextApiResponse) => {
return {
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
email: { label: "Email", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(
credentials: Record<"email" | "password", string> | undefined,
req
): Promise<Omit<User, "id"> | { id?: string | undefined } | null> {
// Add logic here to look up the user from the credentials supplied
const response = await login(
credentials?.email!,
credentials?.password!
);
const cookies = response.headers["set-cookie"];
res.setHeader("Set-Cookie", cookies);
if (response) {
var user = { token: response.data.token, data: response.data.user };
return user;
} else {
return null;
}
},
}),
],
refetchInterval: 1 * 24 * 60 * 60,
secret: process.env.NEXTAUTH_SECRET,
debug: true,
session: {
strategy: "jwt" as SessionStrategy,
maxAge: 3 * 24 * 60 * 60,
},
jwt: {
maxAge: 3 * 24 * 60 * 60,
},
callbacks: {
jwt: async ({ token, user }: { token: JWT; user?: User }) => {
user && (token.accessToken = user.token);
user && (token.user = user.data);
return token;
},
session: async ({ session, token }: { session: Session; token: JWT }) => {
session.user = token.user;
session.accessToken = token.accessToken;
return session;
},
},
};
};
export default (req: NextApiRequest, res: NextApiResponse) => {
return NextAuth(req, res, nextAuthOptions(req, res));
};
I have implemented a next-auth authentication system for my Next.js app. In the providers, I have chosen credentials because I have a node.js backend server.
The problem that I am facing is the expiration of next auth session is not in sync up with the expiration of jwt token on my backend. This is leading to inconsistency. Kindly help me out.
Below is my next auth code
import NextAuth, {
NextAuthOptions,
Session,
SessionStrategy,
User,
} from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { login } from "@actions/auth";
import { toast } from "react-toastify";
import { JWT } from "next-auth/jwt";
import { NextApiRequest, NextApiResponse } from "next";
import { SessionToken } from "next-auth/core/lib/cookie";
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
const nextAuthOptions = (req: NextApiRequest, res: NextApiResponse) => {
return {
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
email: { label: "Email", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(
credentials: Record<"email" | "password", string> | undefined,
req
): Promise<Omit<User, "id"> | { id?: string | undefined } | null> {
// Add logic here to look up the user from the credentials supplied
const response = await login(
credentials?.email!,
credentials?.password!
);
const cookies = response.headers["set-cookie"];
res.setHeader("Set-Cookie", cookies);
if (response) {
var user = { token: response.data.token, data: response.data.user };
return user;
} else {
return null;
}
},
}),
],
refetchInterval: 1 * 24 * 60 * 60,
secret: process.env.NEXTAUTH_SECRET,
debug: true,
session: {
strategy: "jwt" as SessionStrategy,
maxAge: 3 * 24 * 60 * 60,
},
jwt: {
maxAge: 3 * 24 * 60 * 60,
},
callbacks: {
jwt: async ({ token, user }: { token: JWT; user?: User }) => {
user && (token.accessToken = user.token);
user && (token.user = user.data);
return token;
},
session: async ({ session, token }: { session: Session; token: JWT }) => {
session.user = token.user;
session.accessToken = token.accessToken;
return session;
},
},
};
};
export default (req: NextApiRequest, res: NextApiResponse) => {
return NextAuth(req, res, nextAuthOptions(req, res));
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我有一个类似的设置:在客户端上使用带有 jwt 和单独后端会话令牌的凭证身份验证的 NextAuth(版本 4)和 Next.js(带有 App Router 的版本 13)。
这就是我们保持会话同步的方式:
正如其他人提到的,在 NextAuthOptions 中,设置 maxAge 属性设置为与后端服务器上的令牌相同的过期时间。
在经过身份验证的页面的路由树的顶层,检查您的客户端会话是否即将过期,如果是,则刷新令牌。我使用 NextAuth useSession update< 刷新客户端上的令牌/a> 函数并向后端 API 发送请求以更新服务器上的令牌过期时间。这将添加到顶层层次结构中的
layout.tsx
文件中,以便任何需要经过身份验证才能查看的视图。--layout.tsx--
如果您还想添加功能来确定用户在延长会话之前是否处于空闲状态,您可以使用 反应空闲计时器。
--完整的layout.tsx文件--
I have a similar setup: NextAuth (version 4) with Next.js (version 13 with App Router) on the client using credential authentication with a jwt and a separate backend session token.
This is how we keep the sessions in sync:
As others mentioned, in the NextAuthOptions, set the maxAge property to the same expiration time as the token on the back end server.
At the top level of the route tree for your authenticated pages, check if your client-side session is about to expire and if so, refresh the token. I refresh the token on the client-side with the NextAuth useSession update function and send a request to the backend API to update the token expiration on the server. This is added to the
layout.tsx
file in the top level hierarchy for any views that should be authenticated to see.--layout.tsx--
If you also want to add functionality to determine if the user is idle or not before extending their session, you can use react-idle-timer.
--full layout.tsx file--
在您的选项中,有
maxAge
属性。将其设置为等于您在后端服务器中设置的任何时间。时间以秒为单位,因此您当前设置为 3 天。请参阅此处
In your options, there is the
maxAge
property. Set it to be equal to whatever time you have set in your backend server. The time is in seconds, so yours is currently set to 3days.See here
不确定这是否对任何人有帮助,但我无法弄清楚如何阻止应用程序在每次闲置或离开页面并返回时发出新令牌,因此我放弃了尝试同步它们。相反,我只是将它们作为附加属性包含在令牌中。所以我的中间件可以知道令牌何时过期。
Not sure if this helps anyone, but I could not figure out how to keep the app from issuing new tokens every time I idled or left the page and came back, so I gave up on trying to sync them. And instead am just including them in the token as additional properties. So my middleware can know when the token is expired.
我找到了一个解决方案,您可以尝试将 jwt cookie 保存在会话令牌内并从那里读取它,它们将同时过期
查看此以获取更多信息 https://github.com/nextauthjs/next-auth/讨论/1290
I found a solution you can try to save the jwt cookie inside session token and read it from there and they will expiry both at the same time
check this out for more info https://github.com/nextauthjs/next-auth/discussions/1290