Next.js Discord

Discord Forum

http://localhost:3000/api/auth/callback/credentials unauthorized

Answered
Prairie yellowjacket posted this in #help-forum
Open in Discord
Prairie yellowjacketOP
Hey, using next-auth 4.24.5 version and on credentials provider I get an unauthorized error

code is in the comment bellow
{
    "error": "CredentialsSignin",
    "status": 401,
    "ok": false,
    "url": null
}
Answered by Ray
 const result = await signIn("credentials", {
      redirect: false,
      email: data.email,
      password: data.password,
    });

email not username
View full answer

40 Replies

Prairie yellowjacketOP
import { AuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import GoogleProvider from "next-auth/providers/google";
import FacebookProvider from "next-auth/providers/facebook";
import NextAuth from "next-auth/next";
import jwt from "jsonwebtoken";

export const authOptions: AuthOptions = {
  pages: {
    signIn: "/auth/login",
  },

  providers: [
    CredentialsProvider({
      type: "credentials",

      credentials: {
        email: {
          label: "Email",
          type: "text",
        },
        password: {
          label: "Password",
          type: "password",
        },
      },
      async authorize(credentials) {
        if (!credentials?.email || !credentials?.password) return null;
        const credentialDetails = {
          email: credentials.email,
          password: credentials.password,
        };
        console.log("hello");
        const res = await fetch(
          process.env.NEXT_PUBLIC_BACKEND_API + "/auth/login",
          {
            method: "POST",
            body: JSON.stringify(credentialDetails),
            headers: {
              "Content-Type": "application/json",
            },
          }
        );

        if (!res.ok) {
          return null;
        }
        const user = await res.json();
        console.log("logging in:", user);
        return user;
      },
    }),
  ],
};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };


const loginUser: SubmitHandler<InputType> = async (data, e) => {
    if (error) setError("");
    const result = await signIn("credentials", {
      redirect: false,
      username: data.email,
      password: data.password,
    });
    console.log(result);
    if (!result?.ok) {
      toast.error(result?.error);
      setError(result?.error ?? "");
      return;
    }
    toast.success("Welcome To Sakura Dev Channel");
    router.push("/");
  };
// layout
  return (
    <html
      lang="en"
      className={`${aeronik.variable} ${machina.variable} font-aeronik`}
    >
      <body>
        <Providers>
          <div className="logo-gradient absolute inset-0 h-screen w-screen" />
          <div className="text-gradient absolute inset-0 h-screen w-screen bg-transparent" />
          <Toaster position="top-center" />
          {children}
        </Providers>
      </body>
    </html>

// provider
"use client";

import { SessionProvider } from "next-auth/react";

export function Providers({ children }: { children: React.ReactNode }) {
  return <SessionProvider>{children}</SessionProvider>;
}
@Prairie yellowjacket js import { AuthOptions } from "next-auth"; import CredentialsProvider from "next-auth/providers/credentials"; import GoogleProvider from "next-auth/providers/google"; import FacebookProvider from "next-auth/providers/facebook"; import NextAuth from "next-auth/next"; import jwt from "jsonwebtoken"; export const authOptions: AuthOptions = { pages: { signIn: "/auth/login", }, providers: [ CredentialsProvider({ type: "credentials", credentials: { email: { label: "Email", type: "text", }, password: { label: "Password", type: "password", }, }, async authorize(credentials) { if (!credentials?.email || !credentials?.password) return null; const credentialDetails = { email: credentials.email, password: credentials.password, }; console.log("hello"); const res = await fetch( process.env.NEXT_PUBLIC_BACKEND_API + "/auth/login", { method: "POST", body: JSON.stringify(credentialDetails), headers: { "Content-Type": "application/json", }, } ); if (!res.ok) { return null; } const user = await res.json(); console.log("logging in:", user); return user; }, }), ], }; const handler = NextAuth(authOptions); export { handler as GET, handler as POST }; js const loginUser: SubmitHandler<InputType> = async (data, e) => { if (error) setError(""); const result = await signIn("credentials", { redirect: false, username: data.email, password: data.password, }); console.log(result); if (!result?.ok) { toast.error(result?.error); setError(result?.error ?? ""); return; } toast.success("Welcome To Sakura Dev Channel"); router.push("/"); };
where do you use loginUser function?
Prairie yellowjacketOP
it is actually rendered in app layout which consist client component and inside that client component I'm rendering Login for if pathname === "/auth/login"
bit complicated but that's how it is
and sorry loginUser is in that login component
could you show the code for the login component?
Prairie yellowjacketOP
of course, it's bit long so there it is in message.txt
@Prairie yellowjacket of course, it's bit long so there it is in message.txt
ok try this
async authorize(credentials) {
        if (!credentials?.email || !credentials?.password) return null;
        const credentialDetails = {
          email: credentials.email,
          password: credentials.password,
        };
        console.log("hello");
        try {
          const res = await fetch(
            process.env.NEXT_PUBLIC_BACKEND_API + "/auth/login",
            {
              method: "POST",
              body: JSON.stringify(credentialDetails),
              headers: {
                "Content-Type": "application/json",
              },
            }
          );
  
          if (!res.ok) {
            return null;
          }
          const user = await res.json();
          console.log("logging in:", user);
          return user;
        } catch (e) {
          console.log(e)
          return null
        }
      },
Prairie yellowjacketOP
still getting the same error, problem is I don't even get this console.log("hello");
in my terminal it is not even getting to the authorize function
and try to sign in with the default form
Prairie yellowjacketOP
I commented out
  // pages: {
  //   signIn: "/auth/login",
  // },

and there is some error yeah
Prairie yellowjacketOP
I'm reading about error, oh my god is my folder structure ok?
just a momment
Prairie yellowjacketOP
so right now I have my custom jwt decode and encode funcition, I tried even the simplest implementation but same error
@Ray oh wait the url should be /api/auth/signin
Prairie yellowjacketOP
oh lmao there it is
I'll test it right now
/api/auth/signin working ,no flows
so change the url here should work process.env.NEXT_PUBLIC_BACKEND_API + "/auth/login",
Prairie yellowjacketOP
wait I don't get it, this is an api call on my backend
@Ray oh yeah sorry lol
try this
const loginUser: SubmitHandler<InputType> = async (data, e) => {
    if (error) setError("");
    const result = await signIn("credentials", {
      //redirect: false,
      username: data.email,
      password: data.password,
    });
    console.log(result);
    if (!result?.ok) {
      toast.error(result?.error);
      setError(result?.error ?? "");
      return;
    }
    toast.success("Welcome To Sakura Dev Channel");
    router.push("/");
  };
Prairie yellowjacketOP
it redirects me to that page showing an error, I'm sure that data is right, and in my console I didn't see the hello log so it didn't trigger authorize function again
actually my bad I forgot to uncomment
pages: {
    signIn: "/auth/login",
  },
but still same
it's weird throws me to this url:
http://localhost:3000/auth/login?callbackUrl=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Flogin&error=CredentialsSignin
and still same thing about not triggering the authorize function and it refreshes the page where I lose my login data
@Prairie yellowjacket it's weird throws me to this url: http://localhost:3000/auth/login?callbackUrl=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Flogin&error=CredentialsSignin and still same thing about not triggering the authorize function and it refreshes the page where I lose my login data
async authorize(credentials) {
    console.log("hello");
        if (!credentials?.email || !credentials?.password) return null;
        const credentialDetails = {
          email: credentials.email,
          password: credentials.password,
        };
    
        const res = await fetch(
          process.env.NEXT_PUBLIC_BACKEND_API + "/auth/login",
          {
            method: "POST",
            body: JSON.stringify(credentialDetails),
            headers: {
              "Content-Type": "application/json",
            },
          }
        );

        if (!res.ok) {
          return null;
        }
        const user = await res.json();
        console.log("logging in:", user);
        return user;
      },
    }),
try to move the console.log above
 const result = await signIn("credentials", {
      redirect: false,
      email: data.email,
      password: data.password,
    });

email not username
Answer
Prairie yellowjacketOP
oh my Goooood, I'm so sorry for taking your time for this error, thank you very much you are so helpful 🙂
have a good day brother!
Dwarf Crocodile
Hello
I have the same issue:

here is my implementation in the attached file
route.ts file
In my case its working local machine but I get this error in production