How can i hit nextauth sign in with postman?

Viewed 230

Currently i'm trying to create user authentication with NextAuth. I'm able to use it inside my webapp and there is no problem with it. But now, i'm trying to hit the sign in with postman. So i can share the login end point. Here is my [...nextauth].js

const configuration = {  
    secret: process.env.NEXTAUTH_SECRET,
    cookie: {
        secure: process.env.NODE_ENV && process.env.NODE_ENV === 'production',
    },
    session: {
        strategy: "jwt",
        maxAge: 30 * 24 * 60 * 60
    },
    providers: [
        CredentialsProvider({
            id: "credentials",
            name: "credentials",
            credentials: {},
            page: "/",
            async authorize(credentials) {
                try
                {   
                    const user = await prisma.user.findFirst({
                        where: {
                            email: credentials.email
                        }
                    });

                    if (user !== null)
                    {
                        const res = await confirmPasswordHash(credentials.password, user.password);
                        if (res === true)
                        {
                           
                      
                            return user;
                        }
                        else
                        {
                            console.log("Hash not matched logging in");
                            return null;
                        }
                    }
                    else {
                        return null;
                    }
                }
                catch (err)
                {
                    console.log("Authorize error:", err);
                }

            }
        }),
    ],
    callbacks: {
        async session({ session, user, token }) {
            session.user = token.user;
            return session;
          },
       
          async jwt({ token, user, account, profile, isNewUser }) {
            if (user) {
                token.user = user;
              }
              return token;
        },
  
    }
}
export default (req, res) => NextAuth(req, res, configuration)

When i hit via postman, it is returning HTML view.

{
    "email":"myemail@email.com",
    "password":"12345678"
}

and the data will hit to http://localhost:3000/api/auth/signin

How can i achieve it ? thanks in advance

1 Answers

I'm not a Next.js or NextAuth user myself, but looking at the signin page : https://github.com/nextauthjs/next-auth/blob/2469e44572f23f709fa8c5c65c6b7a4eb2383e9f/packages/next-auth/src/core/pages/signin.tsx

We can see that "credentials" type providers render a form that "POST" to the "callback" url.

            {provider.type === "credentials" && (
              <form action={provider.callbackUrl} method="POST">
                <input type="hidden" name="csrfToken" value={csrfToken} />
                {Object.keys(provider.credentials).map((credential) => {
                  return (
                    <div key={`input-group-${provider.id}`}>
                      <label
                        className="section-header"
                        htmlFor={`input-${credential}-for-${provider.id}-provider`}
                      >
                        {provider.credentials[credential].label ?? credential}
                      </label>
                      <input
                        name={credential}
                        id={`input-${credential}-for-${provider.id}-provider`}
                        type={provider.credentials[credential].type ?? "text"}
                        placeholder={
                          provider.credentials[credential].placeholder ?? ""
                        }
                        {...provider.credentials[credential]}
                      />
                    </div>
                  )
                })}
                <button type="submit">Sign in with {provider.name}</button>
              </form>
            )}

That form is expected to have a csrfToken which, if I understand this correctly, you can obtain yourself from /api/auth/csrf (https://next-auth.js.org/getting-started/rest-api#get-apiauthcsrf)

You should be able to inspect the rendered page to find out what the callback URL is for you, presumably /api/auth/signin/:provider but with the actual provider.

As for postman (or your mobile app), I expect that all you need to do is to POST to that URL. The request body will presumably need to be sent as application/x-www-form-urlencoded since the method is POST. Based on what I can understand from your question, the form should have 3 plain fields, email, password and csrfToken, but your email and password field names will be formatted as input-${credential}-for-${provider.id}-provider. Again, inspecting the rendered page and the network request will confirm the correct values.

Oh, and sorry for all the guesses. Hopefully there is still something useful in there.

Related