【问题标题】:NextAuth authentication not working on Deployment on Vercel (Working on localhost)NextAuth 身份验证不适用于 Vercel 上的部署(在本地主机上工作)
【发布时间】:2022-07-28 13:53:14
【问题描述】:

使用凭据进行身份验证与 nextauth。我的代码不适用于 vercel 部署,而是在 localhost 上运行。

我使用基本凭据来验证用户名和密码,但在从页面文件夹中的 SignUpPage 注册后无法获取会话对象

[...nextauth].js

export default NextAuth({
  session: {
    jwt: true,
  },
  providers: [
    Credentials({
      async authorize(credentials) {
        const client = await MongoClient.connect(process.env.MONGO_URI, {
          useNewUrlParser: true,
          useUnifiedTopology: true,
        });

        const usersCollection = client.db().collection("users");

        const user = await usersCollection.findOne({
          username: credentials.username,
        });

        if (!user) {
          client.close();
          throw new Error("No user found!");
        }

        const isValid = await compare(credentials.password, user.password);

        if (!isValid) {
          client.close();
          throw new Error("Could not log you in!");
        }

        client.close();
        return { username: user.username };
      },
    }),
  ],
  callbacks: {
    jwt: async ({ token, user }) => {
      if (user) {
        token.user = user;
      }
      return token;
    },
    session: async ({ session, token }) => {
      if (token) {
        session.user = token.user;
      }
      return session;
    },
  },
  secret: process.env.SECRET,
  jwt: {
    secret: process.env.SECRET,
    encryption: true,
  },
});

pages/api/auth/signup.js

async function handler(req, res) {
  if (req.method !== "POST") {
    return;
  }

  const data = req.body;

  const { username, password } = data;

  if (!username || !password || password.trim().length < 7) {
    res.status(422).json({
      message:
        "Invalid input - password should also be at least 7 characters long.",
    });
    return;
  }

  const client = await MongoClient.connect(process.env.MONGO_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });

  const db = client.db();

  const existingUser = await db
    .collection("users")
    .findOne({ username: username });

  if (existingUser) {
    res.status(422).json({ message: "User exists already!" });
    client.close();
    return;
  }

  const hashedPassword = await hash(password, 12);

  const result = await db.collection("users").insertOne({
    username: username,
    password: hashedPassword,
  });

  res.status(201).json({ message: "Created user!" });
  client.close();
}

export default handler;

pages/SignUpPage.js

useEffect(() => {
    getSession().then((session) => {
      if (session) {
        router.push("/");
      } else {
        setIsLoading(false);
      }
    });
  }, [router]);

  if (isLoading) {
    return <p>Loading...</p>;
  }

  const createUser = async (username, password) => {
    const response = await fetch("/api/auth/signup", {
      method: "POST",
      body: JSON.stringify({ username, password }),
      headers: {
        "Content-Type": "application/json",
      },
    });
    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.message || "Something went wrong!");
    }

    return data;
  };

  const submitHandle = async (username, password) => {
    if (login) {
      const result = await signIn("credentials", {
        redirect: false,
        username: username,
        password: password,
      });

      if (!result.error) {
        router.push("/");
      }
    } else {
      try {
        const result = await createUser(username, password);
        console.log("result", result);
        router.push("/");
      } catch (error) {
        console.log(error);
      }
    }
  };

【问题讨论】:

  • 您是否遇到任何错误?

标签: authentication next.js next-auth


【解决方案1】:

你有没有发现任何与此相关的东西?

我一直在探讨这个问题,但似乎无法弄清楚交易是什么

【讨论】:

    猜你喜欢
    • 2021-09-14
    • 1970-01-01
    • 2021-07-07
    • 2013-07-30
    • 2021-05-07
    • 1970-01-01
    • 2022-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多