Next-Auth使用凭据登录在NextJS中不工作

bwleehnv  于 12个月前  发布在  其他
关注(0)|答案(3)|浏览(152)

我正在将next-auth包集成到我的新Next.js项目中。我已经遵循了所有的Next.js和next-auth文档,但无法找到解决方案。
我面临的问题是这样的:我想使用提交到运行在Laravel上的API服务器的电子邮件和密码登录我的Next.js应用程序。当提交登录表单时,我执行下面的函数。

import { signIn } from "next-auth/client";

const loginHandler = async (event) => {
    event.preventDefault();

    const enteredEmail = emailInputRef.current.value;
    const enteredPassword = passwordInputRef.current.value;

    const result = await signIn("credentials", {
        redirect: false,
        email: enteredEmail,
        password: enteredPassword,
    });

    console.log("finished signIn call");
    console.log(result);
};

下面显示的代码是在我的pages/api/auth/[...nextauth].js

import axios from "axios";
import NextAuth from "next-auth";
import Providers from "next-auth/providers";

export default NextAuth({
    session: {
        jwt: true,
    },
    providers: [
        Providers.Credentials({
          async authorize(credentials) {
            axios
              .post("MY_LOGIN_API", {
                email: credentials.email,
                password: credentials.password,
              })
              .then(function (response) {
                console.log(response);
                return true;
              })
              .catch(function (error) {
                console.log(error);
                throw new Error('I will handle this later!');
              });
          },
        }),
    ],
});

但是当尝试使用正确/不正确的凭据登录时,我在Google Chrome控制台日志中得到以下错误。

POST http://localhost:3000/api/auth/callback/credentials? 401 (Unauthorized)
{error: "CredentialsSignin", status: 401, ok: false, url: null}

我是不是漏掉了什么?

6jjcrrmo

6jjcrrmo1#

来自文档(https://next-auth.js.org/providers/credentials#example)

async authorize(credentials, req) {
  // Add logic here to look up the user from the credentials supplied
  const user = { id: 1, name: 'J Smith', email: '[email protected]' }

  if (user) {
    // Any object returned will be saved in `user` property of the JWT
    return user
  } else {
    // If you return null or false then the credentials will be rejected
    return null
    // You can also Reject this callback with an Error or with a URL:
    // throw new Error('error message') // Redirect to error page
    // throw '/path/to/redirect'        // Redirect to a URL
  }
}

您当前没有从authorize回调返回用户或null

ljo96ir5

ljo96ir52#

shanewwarren发布的答案是正确的,但这里是更详细的答案,
使用axios来解决这个问题

async authorize(credentials, req) {
        return axios
          .post(`${process.env.NEXT_PUBLIC_STRAPI_API}/auth/login`, {
            identifier: credentials.identifier,
            password: credentials.password,
          })
          .then((response) => {
            return response.data;
          })
          .catch((error) => {
            console.log(error.response);
            throw new Error(error.response.data.message);
          }) || null;
      },
xvw2m8pv

xvw2m8pv3#

add try/cath inside Apache authorize(credentials){}在那里放一些日志,在我的情况下,我检查日志并通过使用其他节点版本修复了问题

相关问题