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

Can't use auth() to get values from jwt() callback in v5

Open Celsiusss opened this issue 3 years ago • 39 comments

Environment

next: 14.0.2 => 14.0.2 
next-auth: ^5.0.0-beta.3 => 5.0.0-beta.3 
react: ^18 => 18.2.0 

Reproduction URL

https://github.com/Celsiusss/nextauth-demo

Describe the issue

In the documentation, it says that:

When using auth(), the session() callback is ignored. auth() will expose anything returned from the jwt() callback or if using a "database" strategy, from the User. This is because the session() callback was designed to protect you from exposing sensitive information to the client, but when using auth() you are always on the server.

I tried to test this, but could not get values from the jwt() callback to be returned by auth(). It seems like the opposite of what this text says is true. Values from the session() callback is being returned, instead of jwt(). Not quite sure what the intended behavior really is, but I would love to access encrypted token values using auth().

How to reproduce

I have tried to create a minimal example in the Github link.

Here I am using auth() in a server component and in a route handler, to demonstrate it in two different ways. page.tsx shows it being used in a server component. api/route.ts shows it being used in a route handler. client.tsx client component for signing in and using the route handler auth.ts registers an oidc provider and defines the jwt() callback.

Expected behavior

I expected to be able to use auth() to retrieve values from the jwt() callback in server side components.

Celsiusss avatar Nov 12 '23 04:11 Celsiusss

I've encountered the same issue, and it would be fantastic if it worked as described in the documentation. I aim to avoid exposing the access token to the client.

As far as I understand, there isn't a way to obtain the up-to-date JWT in server calls. Although there's a getToken method, it only retrieves the JWT from the request, which might require updating (e.g., refresh token rotation). Getting the updated JWT directly from auth() would resolve this.

czymstef avatar Nov 15 '23 23:11 czymstef

Just ran into this as well after upgrading from a previous beta version. This is a pretty critical bug.

mwawrusch avatar Nov 22 '23 15:11 mwawrusch

I also met the issue and figured out that the migration guide of this part was a little misleading. After tracing the source code, I found that the auth returned by NextAuth was just a getSession call with auth config. According to the documentation, both of the returned values of auth and getSession are Session and Session is the return value of session() callback, so the return value of auth is the return value of session() callback, not the return value of jwt() callback. The return value of jwt() callback will be encoded and set within server side cookie.

If we want auth to contain the returned value of jwt() callback, we can do this within session() callback.

callbacks: {
  session({ session, token }) {
    // token is the returned value of `jwt()`
    return { ...session, ...token }
    // Can just return token if you want.
  }
}

judewang avatar Nov 26 '23 13:11 judewang

@judewang The problem with this approach is that the unencrypted token is exposed to the client.

czymstef avatar Nov 27 '23 11:11 czymstef

@czymstef I supposed we can avoid exposing the token without using useSession, was I wrong? Since we are always on the server, are there any differences that the Session returned from auth is somehow by session() or by jwt() ?

BTW the encrypted token is within cookie.

judewang avatar Nov 27 '23 11:11 judewang

As far as I know, there is still the /api/auth/session endpoint (used by useSession()), which is just one GET-request away. I'm sure that there is a way to "disable" this endpoint (e.g. by defining a no op api route with the same name), but I'd not bet that there is no other way to somehow get the token in a compromised client.

czymstef avatar Nov 27 '23 12:11 czymstef

I got a 404 error when trying to access /api/auth/session. CleanShot 2023-11-27 at 21 43 56@2x

The values within cookie were also encrypted. CleanShot 2023-11-27 at 21 45 37@2x

judewang avatar Nov 27 '23 12:11 judewang

So is there no way at the moment to get the raw token server-side? Seems pretty limiting

alessandrojcm avatar Nov 27 '23 12:11 alessandrojcm

@judewang go to https://next-auth-example.vercel.app/, which should run on next-auth v5 beta. Login using github, then in the developer console write: await fetch("https://next-auth-example.vercel.app/api/auth/session").then(res => res.json()) You should get the result from the session() callback, which is where the token would be leaked if I'd include it in the session.

@alessandrojcm I think there is a way using getToken(), but as far as I know it won't call the jwt() callback and thus does not run stuff like refresh token rotation.

czymstef avatar Nov 27 '23 14:11 czymstef

@czymstef I tried https://next-auth-example.vercel.app and also got my token printed within the console. However when doing the same thing on my site, I still got a 404 error. I noticed that I didn't export the handlers to any api routes, and that was what I found the demo page done, so maybe that caught the leak.

https://github.com/nextauthjs/next-auth/blob/main/apps/examples/nextjs/app/api/auth/%5B...nextauth%5D/route.ts

judewang avatar Nov 27 '23 14:11 judewang

@judewang go to https://next-auth-example.vercel.app/, which should run on next-auth v5 beta. Login using github, then in the developer console write: await fetch("https://next-auth-example.vercel.app/api/auth/session").then(res => res.json()) You should get the result from the session() callback, which is where the token would be leaked if I'd include it in the session.

@alessandrojcm I think there is a way using getToken(), but as far as I know it won't call the jwt() callback and thus does not run stuff like refresh token rotation.

Yeah I noticed getToken only decodes the token from the cookies, that may or not be enough depending on your use case; still I believe the library should offer a native way or getting the token as it was in v4. Alternatively one could export the function that does token rotation an call that beofore of getToken, although that is not ideal.

As per adding the token to the session callback, I think that could be done and, to avoid leaking the token, one could catcth the call to api/auth/session within the route handler and just strip the token from the response. Although you'd need to be very careful where you call getSession to avoid leaking the token.

alessandrojcm avatar Nov 27 '23 15:11 alessandrojcm

@alessandrojcm Mind sharing how you could get the token server side in v4? I thought that this was not possible, too (with refresh token rotation and all).

@judewang If you don't export the handlers, then the callback endpoint does not exist, too, which makes logging in impossible, doesn't it? But we could only export the required handlers and just don't export the session one, or as @alessandrojcm suggested: Catch the call to /session and strip it. But who says that authjs won't add a method at a later stage which uses server actions?

This is just not as the library is intended to be used; session() is for client side data. I don't think you should have to jump through those hoops to just get the (possibly refreshed, including new Set-Cookie headers) value from jwt() on server side.

czymstef avatar Nov 27 '23 15:11 czymstef

@alessandrojcm Mind sharing how you could get the token server side in v4? I thought that this was not possible, too (with refresh token rotation and all).

@judewang If you don't export the handlers, then the callback endpoint does not exist, too, which makes logging in impossible, doesn't it? But we could only export the required handlers and just don't export the session one, or as @alessandrojcm suggested: Catch the call to /session and strip it. But who says that authjs won't add a method at a later stage which uses server actions?

This is just not as the library is intended to be used; session() is for client side data. I don't think you should have to jump through those hoops to just get the (possibly refreshed, including new Set-Cookie headers) value from jwt() on server side.

There is v4's getToken, though now that I think of it I am not entirely sure if that does execute session; you might be right.

And as per your second point, yes you are right one should not rely on patching session since it might either break in the future or we might be leaking the token somewhere else. IMO there should be a way of getting the raw token server-side as we might need it, for examplet to authenticate with 3rd party APIs if necessary.

alessandrojcm avatar Nov 27 '23 15:11 alessandrojcm

Just to add, I am not quite able to get the getToken function from @auth/core/jwt to work. Even tho I am passing the same parmeters to the function that get passed by the library internally; even is this worked I don't think it'd be a good idea to mimic the internals. Maybe @balazsorban44 or someone from the dev team could advice in this case on how to get the raw JWT token?

alessandrojcm avatar Nov 27 '23 17:11 alessandrojcm

Just to emphasize this again: I personally do not only want the raw unencrypted token, but have a refreshed one. In other words: I'm looking for a method to get the content of the jwt() callback including a Set-Cookie header in case the jwt() content changed (e.g. refresh token rotation occured). Something like unstable_getServerSession(), but for the jwt() content instead of session()

If I understand the documentation correctly, getToken() does indeed get the raw token, but it's the token from the cookie, which is potentially stale

czymstef avatar Nov 27 '23 17:11 czymstef

I'm experiencing the same issue. Has there been any update or resolution?

I'm attempting to retrieve user IDs using auth() in Server Components, but returned user object includes only name, email, and image.

const session = await auth();
console.log(session.user) // { image: '...', email: '...', name: '...' }

I ran through the code and figured out that this segment does nothing:

https://github.com/nextauthjs/next-auth/blob/d7a116558700785880ecb03658b7de7c98bcf4bf/packages/next-auth/src/lib/index.ts#L76-L83

Because the supplied args[0].session has hard-coded user which only contains them.

https://github.com/nextauthjs/next-auth/blob/d7a116558700785880ecb03658b7de7c98bcf4bf/packages/core/src/lib/actions/session.ts#L52-L59

G4RDS avatar Jan 02 '24 08:01 G4RDS

@G4RDS I have the same issue, did you find any solution?

eessadrati avatar Jan 13 '24 20:01 eessadrati

@G4RDS does doing the module augmentation had any positive impact on solving the issue? or did you find a solution?

statusunknown418 avatar Jan 16 '24 03:01 statusunknown418

If you need more info from the OIDC provider you can always get it by modifying the session object through the jwt and session callback. Just get whatever you need from the account parameter that gets passed to the jwt callback, then that object gets passed down to session and whatever you return from that you can get through auth. I do it in my app:

  session: ({ session, token }) => {
      // token has the object returned from the jwt callback
     // here you can modify the session object as you please
      session.user = {...session.user, id: token.user.id}
      return session
    },
    jwt: async ({ account, user }) => {
      // account has the user info from the OIDC provider
      if (account) {
        return {
          user: {
              ...user,
             // add whatever property from account
             id: account.id
          },
        }
        // @ts-expect-error
      }
      return user
      }
    },

You can then use module augmentation to get type completion.

alessandrojcm avatar Jan 16 '24 09:01 alessandrojcm

Is any of you guys by any chance using the drizzle-adapter and have the extended session object working?

statusunknown418 avatar Jan 16 '24 22:01 statusunknown418