nextauthjs / next-auth

Authentication for the Web.
https://authjs.dev
ISC License
24.96k stars 3.52k forks source link

Securing Pages & API routes recommends deprecated getToken #10293

Closed jarrodmedrano closed 7 months ago

jarrodmedrano commented 8 months ago

What is the improvement or update you wish to see?

Screenshot 2024-03-12 at 9 20 21 AM

this page recommends next-auth/jwt but if you try to use it, you will get an error.

Screenshot 2024-03-12 at 9 19 49 AM

This should be marked as deprecated or removed to avoid confusion.

Is there any context that might help us understand?

Why is this there, if I can't use it?

Does the docs page already exist? Please link to it.

https://authjs.dev/guides/basics/securing-pages-and-api-routes

michaelzewdu commented 8 months ago

Salt is required on the getToken function but I don't even have a salt on the NextAuth setup. I am using next-auth5.0.0-beta.15 ??

michaelzewdu commented 8 months ago

I don't see the point of using this function anymore. Looks like Next Auth 5 can retrieve the user from the session cookie itself. I just imported auth from NextAuth and called const session = await auth(); and there is my user object. But this only works on the server side

visualcookie commented 8 months ago

I don't see the point of using this function anymore. Looks like Next Auth 5 can retrieve the user from the session cookie itself. I just imported auth from NextAuth and called const session = await auth(); and there is my user object. But this only works on the server side

This does not work for API routes tho. I've tried various attempts now, which are stated in the documentation, along with const session = await auth(req, res). I can't get the current user inside my API route, which is a bummer, since I have to return data specific to the currently signed in user only.

It's also crazy, how unmaintained the documentations are.

jarrodmedrano commented 8 months ago

I don't see the point of using this function anymore. Looks like Next Auth 5 can retrieve the user from the session cookie itself. I just imported auth from NextAuth and called const session = await auth(); and there is my user object. But this only works on the server side

This does not work for API routes tho. I've tried various attempts now, which are stated in the documentation, along with const session = await auth(req, res). I can't get the current user inside my API route, which is a bummer, since I have to return data specific to the currently signed in user only.

It's also crazy, how unmaintained the documentations are.

Have you tried it like this?


import authConfig from "@/auth.config";
import {
  DEFAULT_LOGIN_REDIRECT,
  apiAuthPrefix,
  authRoutes,
  publicRoutes,
} from "@/routes";

const { auth } = NextAuth(authConfig);

export default auth((req) => {
  const { nextUrl } = req;
  const isLoggedIn = !!req.auth;

  const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
  const isPublicRoute = publicRoutes.includes(nextUrl.pathname);
  const isAuthRoute = authRoutes.includes(nextUrl.pathname);

  if (isApiAuthRoute) {
    return null;
  }

  if (isAuthRoute) {
    if (isLoggedIn) {
      return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl))
    }
    return null;
  }

  if (!isLoggedIn && !isPublicRoute) {
    let callbackUrl = nextUrl.pathname;
    if (nextUrl.search) {
      callbackUrl += nextUrl.search;
    }

    const encodedCallbackUrl = encodeURIComponent(callbackUrl);

    return Response.redirect(new URL(
      `/auth/login?callbackUrl=${encodedCallbackUrl}`,
      nextUrl
    ));
  }

  return null;
})

// Optionally, don't invoke Middleware on some paths
export const config = {
  matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
}

This will only work on Edge though. I am not able to use it because I am using pg

visualcookie commented 7 months ago

I don't see the point of using this function anymore. Looks like Next Auth 5 can retrieve the user from the session cookie itself. I just imported auth from NextAuth and called const session = await auth(); and there is my user object. But this only works on the server side

This does not work for API routes tho. I've tried various attempts now, which are stated in the documentation, along with const session = await auth(req, res). I can't get the current user inside my API route, which is a bummer, since I have to return data specific to the currently signed in user only. It's also crazy, how unmaintained the documentations are.

Have you tried it like this?


import authConfig from "@/auth.config";
import {
  DEFAULT_LOGIN_REDIRECT,
  apiAuthPrefix,
  authRoutes,
  publicRoutes,
} from "@/routes";

const { auth } = NextAuth(authConfig);

export default auth((req) => {
  const { nextUrl } = req;
  const isLoggedIn = !!req.auth;

  const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
  const isPublicRoute = publicRoutes.includes(nextUrl.pathname);
  const isAuthRoute = authRoutes.includes(nextUrl.pathname);

  if (isApiAuthRoute) {
    return null;
  }

  if (isAuthRoute) {
    if (isLoggedIn) {
      return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl))
    }
    return null;
  }

  if (!isLoggedIn && !isPublicRoute) {
    let callbackUrl = nextUrl.pathname;
    if (nextUrl.search) {
      callbackUrl += nextUrl.search;
    }

    const encodedCallbackUrl = encodeURIComponent(callbackUrl);

    return Response.redirect(new URL(
      `/auth/login?callbackUrl=${encodedCallbackUrl}`,
      nextUrl
    ));
  }

  return null;
})

// Optionally, don't invoke Middleware on some paths
export const config = {
  matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
}

This will only work on Edge though. I am not able to use it because I am using pg

Tried this idea too, but still that does not seem to work at all and even gives me a redirection error. Since I'm using Drizzle with a PG DB, I will now submit an API call with a custom header.

const session = await auth()
console.log(session?.user)
const data = await fetch('http://localhost:3000/api/pressure', {
  headers: {
    'X-User-Id': session?.user?.id as string,
  },
}).then((res) => res.json())
console.log(data)
ndom91 commented 7 months ago

We shipped updated docs the other day and they include a specific section on "getting user session" which should be more straight forward to use :pray:

https://authjs.dev/getting-started/session-management?sessionTab=get-session

ndom91 commented 7 months ago

I'm going to close this issue as getToken has been deprecated in v5 and the new docs no longer recommend it

figure002 commented 7 months ago

We shipped updated docs the other day and they include a specific section on "getting user session" which should be more straight forward to use 🙏

https://authjs.dev/getting-started/session-management?sessionTab=get-session

I'm getting a 404