如何在NextAuth中根据用户选择增加会话过期时间?



我在Next.js应用程序中使用Next-Auth进行身份验证,我使用凭据提供程序。在登录页面,有一个选项让用户记住他们的密码。

当选择此选项时,我想增加会话过期时间。如果不设置,则设置为24小时。

Login.js代码:

const handleSubmit = async (e) => {
e.preventDefault();
const res = await signIn("credentials", {
redirect: false,
username: username,
password: password,
rememberPassword: checked,
});
if (res?.error) {
console.log(res.error)
} else {
push("/");
}
};

[…nextauth] . js代码:

export const authOptions = {
providers: [
CredentialsProvider({
name: "credentials",
async authorize(credentials) {
...
//I can access rememberPassword here, for example :
const rememberPassword = credentials.rememberPassword;
},
}),
],
secret: SECRET_KEY,
jwt: {
secret: SECRET_KEY,
encryption: true,
},
session: {
jwt: true,
**    maxAge: req.body.rememberPassword ? 15 * 24 * 60 * 60 : 24 * 60 * 60, //I want something like this**
},
};
export default NextAuth(authOptions);

我在访问会话属性中的rememberPassword时遇到麻烦。

您可以使用高级初始化来动态实例化选项。要设置会话过期时间,可以这样做:

// pages/api/auth/[...nextauth].js
import NextAuth from "next-auth";
export default async function auth(req, res) {
// Do whatever you want here, before the request is passed down to NextAuth
return await NextAuth(req, res, {
// Other options go here 👈🏽
session: {
jwt: true,
// 👇🏽 Your dynamic session
maxAge: req.body.rememberPassword ? 15 * 24 * 60 * 60 : 24 * 60 * 60,
},
});
}

相关内容

  • 没有找到相关文章

最新更新