使用凭证进行 Next-Auth 登录在 NextJS 中不起作用

Lal*_*mar 16 javascript next.js next-auth

我正在将 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);
};
Run Code Online (Sandbox Code Playgroud)

下面显示的代码在我的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!');
              });
          },
        }),
    ],
});
Run Code Online (Sandbox Code Playgroud)

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

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

我在这里错过了什么吗?

sha*_*ren 9

来自文档(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: 'jsmith@example.com' }

  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
  }
}
Run Code Online (Sandbox Code Playgroud)

您当前没有返回用户或nullauthorize回调中返回。


Soh*_*ekh 5

shannewwarren 发布的答案是正确的,但这里有更详细的答案,

使用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;
      },
Run Code Online (Sandbox Code Playgroud)