next-auth icon indicating copy to clipboard operation
next-auth copied to clipboard

getToken returning null when calling from server component using authorization header and returning encoded token when using raw option

Open jay-rt opened this issue 2 years ago • 1 comments

Environment

System: OS: Windows 10 10.0.19045 CPU: (4) x64 Intel(R) Core(TM) i5-7200U CPU @ 2.50GHz
Memory: 9.61 GB / 15.90 GB Binaries: Node: 18.12.0 - C:\Program Files\nodejs\node.EXE npm: 8.19.2 - C:\Program Files\nodejs\npm.CMD Browsers: Edge: Spartan (44.19041.1266.0), Chromium (115.0.1901.188) Internet Explorer: 11.0.19041.1566

Reproduction URL

https://github.com/jay-rt/generic

Describe the issue

Whenever calling API from server components using authorization header, the getToken function returns null. However, if you set the raw option, you get encoded token.

How to reproduce

You can download the repository and then set up 4 environment variables NEXTAUTH_SECRET, NEXTAUTH_URL, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET. After that, login in by visiting the page http://localhost:3000/api/auth/signin and click one of the buttons: secret - client component, secret - server component image When clicking client component, you can visit the secret page but when you use server component, you see the message sign in even though you are already sign in. image To change this comment, out the token = getToken({req}) and uncomment the token = getToken({req, raw: true)} in middleware.js and you can recieve the raw token. image image

Expected behavior

getToken should be able to return the decoded token and not return null

jay-rt avatar Aug 02 '23 17:08 jay-rt

Use getToken() only for securing API routes, not in your middleware. In middleware.js you can use export { default } from "next-auth/middleware" to protect all pages, like described in https://next-auth.js.org/tutorials/securing-pages-and-api-routes.

JasperAlexander avatar Apr 21 '24 12:04 JasperAlexander