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

frebpwbc  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(119)

我在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 code:

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时遇到问题。

xdnvmnnf

xdnvmnnf1#

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

// 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,
    },
  });
}

相关问题