简体   繁体   中英

Next-Auth signIn with Credentials is not working in NextJS

I'm integrating next-auth package to my fresh Next.js project. I have followed all of the Next.js and next-auth documentations but not able to find a solution.

The issue I'm facing goes like this: I want to Login to my Next.js app using Email & Password submitted to my API Server running on Laravel. When submitting the login form I'm executing the below function.

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

And code shown below is in my 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!');
              });
          },
        }),
    ],
});

But when try to login with correct/incorrect credentials, I get the below error in Google Chrome console log.

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

Am I missing something here?

From the documentation ( 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
  }
}

You are not currently returning a user or null from the authorize callback.

Answer posted by shanewwarren is correct, but here is more elaborated answer,

Using axios to solve this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM