falcon lover
falcon lover

Reputation: 87

Next-Auth: getSession returns null

API request for the below code through a browser works fine i.e. returns {"success":true,"data":{"user": ...}} but using cURL or REST-Client VS Code extension return null i.e. {"success":true,"data":null}. Below is the code where I return the session object through /api/query endpoint:

import { getSession } from "next-auth/client";

export default async (req, res) => {
  const session = await getSession({ req });
  res.status(200).json({ success: true, data: session });
};

I tried getting the session using the endpoint /api/auth/session too. The endpoint returns the session using the browser but returns null using cURL. Here is the cURL request curl http://localhost:3000/api/auth/session.
What's the reason for the behavior?

P.S. : I am using Google OAuth for authentication.

Upvotes: 3

Views: 9218

Answers (4)

Victor Honorato
Victor Honorato

Reputation: 11

create file: ' .eslintrc.json ' in the root of the application with the following contents:

{
  "env":{"browser": true, "node":true, "es6":true},
  "extends": ["eslint:recommended","next/core-web-vitals"]
}

Upvotes: 0

Greg
Greg

Reputation: 1991

There is curl support for cookies. I have used the following to authenticate using curl and the NextAuth credential provider:

API_URL=http://localhost:3000

# CSRF token curl can parsed manually or with SED if JQ not installed
CSRF_TOKEN=$(curl -c /tmp/nextauth-cookies.txt -b /tmp/nextauth-cookies.txt $API_URL/api/auth/csrf | jq -r '.csrfToken')

# Login
curl -v \
  -d "username=agoodusername&password=agoodpassword&csrfToken=${CSRF_TOKEN}" \
  -c /tmp/nextauth-cookies.txt \
  -b /tmp/nextauth-cookies.txt \
  $API_URL/api/auth/callback/credentials

# Logout
curl -v \
  -d "csrfToken=${CSRF_TOKEN}" \
  -c /tmp/nextauth-cookies.txt \
  -b /tmp/nextauth-cookies.txt \
  $API_URL/api/auth/signout

agoodusername and agoodpassword should both be updated (URL-encoded values).

NextAuth uses the double submit method to prevent CSRF attacks, so CSRF token needs to be included in form data as well as request cookies.

Upvotes: 1

Advena
Advena

Reputation: 2233

In next-auth v4, getting the clients session in a Middleware is currently not supported. You can use the built in Middleware methods (which will eventually hit the getToken method) - or use getToken yourself.

I myself feel that this should be highlighted more in the documentation.

Source: This reddit post with an approved comment from lrobinson, VP of Developer Experience @ Vercel

Upvotes: 3

Ivan V.
Ivan V.

Reputation: 8081

Auth depends on cookies, your browser automatically sends the cookies. But when you use cURL cookies are not present, hence auth cannot authenticate. Next-Auth cookies

Upvotes: 6

Related Questions