Is there a way to perform a nextAuth sign in using Postman?

I am currently working on implementing user authentication using NextAuth. The authentication works perfectly within my webapp, but now I want to test the sign-in functionality using Postman so that I can share the login endpoint. Below is the configuration in my [...nextauth].js file:

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 making a request via Postman, it returns an HTML view.

{
    "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="412c38242c20282d01242c20282d6f222e2c">[email protected]</a>",
    "password":"12345678"
}

The data will be sent to

http://localhost:3000/api/auth/signin
. How can I achieve this successfully? Thank you in advance.

Answer №1

To access your account, log in through the web browser and retrieve the following cookies:

next-auth.callback-url=value; next-auth.csrf-token=value; next-auth.session-token=value
. Once obtained, utilize these cookies by adding them to the postman request headers under the Cookie section.

Answer №2

Although I am not personally a user of Next.js or NextAuth, taking a look at the signin page: https://github.com/nextauthjs/next-auth/blob/2469e44572f23f709fa8c5c65c6b7a4eb2383e9f/packages/next-auth/src/core/pages/signin.tsx

We can observe that providers of type "credentials" display a form that sends a POST request 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>
            )}

This form should include a csrfToken, which you can likely obtain from /api/auth/csrf (https://next-auth.js.org/getting-started/rest-api#get-apiauthcsrf)

You can examine the rendered page to determine the specific callback URL for you, most likely /api/auth/signin/:provider but with the actual provider included.

Regarding Postman (or your mobile app), you will probably just need to make a POST request to that URL. The request body should be sent as

application/x-www-form-urlencoded
since it is a POST method. Based on what you have described, the form should contain 3 plain fields: email, password, and csrfToken, but the field names for email and password should be formatted as
input-${credential}-for-${provider.id}-provider
. By inspecting the rendered page and network requests, you can confirm the correct values.

I apologize for the speculation, but hopefully, there is some helpful information in these insights.

Answer №3

Include a new GET endpoint for obtaining CSRF token:

{{url}}/api/auth/signin

Add Test to this endpoint in Postman using the code below:

console.log("Response: Testing script");

pm.cookies.each(cookie => console.log(cookie));
let csrfToken = pm.cookies.get("next-auth.csrf-token");
// let csrfToken = pm.cookies.get("__Host-next-auth.csrf-token");
let csrfTokenValue = csrfToken.split('|')[0];
let sessionTokenValue = pm.cookies.get("next-auth.session-token");
// let sessionTokenValue = pm.cookies.get("__Secure-next-auth.session-token");

console.log('csrf token value: ', csrfTokenValue);
console.log('session token value: ', sessionTokenValue);

pm.environment.set("csrfToken", csrfTokenValue, "<your-environment-name>");
pm.environment.set("sessionToken", sessionTokenValue, "<your-environment-name>");

"__Host-next-auth.csrf-token" and "__Secure-next-auth.session-token" are used for testing in Postman when deployed on Vercel.

Create a new POST endpoint for logging in and apply the same test:

{{url}}/api/auth/callback/credentials

Start by clicking on the GET token, then proceed with sending login credentials via POST. This will display an HTML view and set essential cookies required for successful login.

To logout, utilize the POST endpoint provided below:

{{url}}/api/auth/signout

Answer №4

When adding Sharukh Rahman's response, make sure to navigate to the Headers section and enter "Cookie" in the Key field, then input "next-auth.session-token=value" in the Value field.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In AngularJS, the $http get method is displaying the status code of the data object instead of

After pondering over this issue for several days, I am still unable to pinpoint what I am doing wrong. Any suggestions or insights would be greatly appreciated. My challenge lies in trying to showcase the response from a rest service to the user by utilizi ...

When a promise is executed, it runs the code synchronously regardless of the promise

Essentially, I have a web application that fetches data from Firebase. Due to the time it takes to retrieve this data, I've implemented promises in JavaScript to ensure my code executes at the appropriate times. Within the function getDataFirebase, in ...

Using AngularJS to display multiple objects in the same ng-repeat loop

Is it possible to display two objects simultaneously in ng-repeat? <tr data-ng-repeat="target in targets |session in sessions |filter:query | orderBy:orderProp"> ...

I have a json file that I need to convert to a csv format

I am currently working with a json file, but I need to switch it out for a csv file. Do I have to use a specific library to accomplish this task, or can I simply modify the jQuery 'get' request from json to csv? I attempted the latter approach, b ...

"Trouble with making jQuery AJAX calls on Internet Explorer versions 8 and 9

I've been searching for the answer to this problem without any luck. I have a page with jquery ajax calls to an API service. It works well in Chrome, Safari, Firefox, and IE 10, but fails in IE 9 and 8. Here is the code: $.ajax({ ...

Looking for guidance on implementing explicit waits in Protractor for non-angular applications

I have noticed that automating non-angular applications with Protractor can be challenging. Currently, I am using some methods to add an explicit wait to my existing Serenity click and enter functions. However, I am curious if there is a way to automatic ...

Ways to display "No records" message when the filter in the material table in Angular returns no results

How can I implement a "No Records Message" for when the current table is displaying empty data? Check out this link for examples of material tables in AngularJS: https://material.angular.io/components/table/examples ...

Is there a way to use JavaScript to automatically open a URL at regular intervals?

List of URLs in JavaScript: var websites = ['https://www.google.com', 'https://www.msn.com', 'https://stackoverflow.com']; I have an array containing multiple website URLs. My goal is to open each URL in a new tab or window e ...

Combining the power of ExpressJS with a dynamic blend of ejs and React for an

My current setup involves a NodeJS application with an Express backend and EJS for the frontend. The code snippet below shows an example route: router.get("/:name&:term", function(req, res) { Course.find({ courseName: req.params.name, courseTerm: req.p ...

Learning how to handle URLEncoded format in Vue JS

Seeking guidance on how to handle URL Encoded format in postman to send data to my Vue JS app. Using the encoded format shown below, what npm package should I utilize for this task? https://i.stack.imgur.com/sBkXi.png ...

Prevent $.ajax with jQuery when a button is clicked

Is there a way to interrupt the $.ajax() function execution by clicking on this button: <button class="stop">Stop</button> Is there a specific function that can cause the $.ajax() call to stop? Note: The $.ajax script is within a function, l ...

Utilize API to import sunrise and sunset times based on specific coordinates directly into a Google Sheet

After countless hours of trying to crack this code, I’m faced with a final hurdle. The challenge lies in parsing the output from the and storing either the sunrise or sunset time into a variable that can be exported as a result in a Google Sheet. The u ...

Seamlessly Loading Comments onto the Page without Any Need for Refresh

I am new to JavaScript and I am trying to understand how to add comments to posts dynamically without needing to refresh the page. So far, I have been successful in implementing a Like button using JS by following online tutorials. However, I need some gui ...

What is the best way to organize Node/Express routes based on their type into different files?

My /router/index.js file is becoming too cluttered, and I want to organize my routes by group (user routes, post routes, gear routes) into separate files within /router/routes/. Here's what I currently have set up: app.js var express = require(&apos ...

Authenticate yourself as a user or an organization on mongodb

I am currently developing an application that requires user registration and login, as well as organization registration and login. I have implemented the use of Node.js Passport with a local strategy for authentication. While I have successfully created t ...

Display modal within a React list

I need to display a list of items with an edit button for each item, which should trigger a modal showing the details of that specific item. Initially, I had a single modal component in the parent element and passing the visible values to the parent state ...

"Enhance your website with a sleek Bootstrap navigation system featuring dividers and

Need help with creating a Bootstrap nav menu similar to this design made in Photoshop? Wondering about the best way to position the logo and create dividers between menu items like shown in this image. Here's the HTML code currently being used: & ...

Improper Alignment of Bootstrap 4 Navbar Link: Troubleshooting Required

Take a look at the image for the issue: https://i.stack.imgur.com/u9aCy.png As shown in the image, the NavBar links are stacked instead of being displayed in one row. This is the HTML code I have used: <!doctype html> <html> <head> ...

Modify the layout of the date selector to display weekdays instead - material ui

How can I change the datepicker format to display weekdays (Monday, Tuesday,..) instead of MM/dd/yyyy? Currently, the datepicker is set up with the format format="MM/dd/yyyy". Would it be possible to modify this? Here is the source code: <MuiPickers ...

Acquiring information from a different Vue.js component

I am faced with a puzzle involving 2 components, A and B. Component A: import B from '../components/B.vue'; export default { components: { B }, methods: { test: function() { console.log(B.data().settin ...