payloadcms / payload-3.0-demo

The official demo for Payload 3.0
https://next-payload-3-0-test.vercel.app
432 stars 139 forks source link

Custom Auth Strategy with Next Auth in Payload Causes 401 Error on User Data Update #110

Closed Livog closed 5 months ago

Livog commented 5 months ago

Custom Auth Strategy Error

Issue: After updating user data when being authenticated using a custom auth strategy. When looking in the network tab a refresh rest endpoint is being called, which causes a 401 Unauthorized error occurs, displaying a "You have been logged out" screen, though the user remains logged in after a refresh.

Steps to Reproduce:

  1. Clone the repository from Payload.3.0.Boilerplate.SaaS.
  2. Add GitHub Secret and ID to .env.
  3. Navigate to the start page /.
  4. Log in using GitHub Auth.
  5. Go to /admin.
  6. Navigate to a user and update their data.
  7. Observe the "You have been logged out" message; however, refreshing the page or clicking on the login button confirms you are still logged in.

Additional Question

Let me know if you need anymore information or you can chat with me on Discord.

jmikrut commented 5 months ago

Hey @Livog — like you said, it looks to me like there might be something to do with the refresh endpoint which Payload's admin UI uses in the background to keep the user logged in as they navigate the admin UI. If you hit that endpoint directly, I bet you'll be able to reproduce the 401 error.

I'm not sure the best way to allow for this to work as you intend. Your auth strategy should refresh the users' session / token in the same way that ours does. You can override the refresh endpoint that is mounted for a given collection, so you might want to look into that - OR, use a beforeOperation hook that looks at operation: 'refresh' to return a response to the user before the actual refresh operation runs.

You are probably hitting the throw new Forbidden(args.req.t) line within our built-in refresh operation, which then causes the user to see the 401, and no user returned from the refresh endpoint, thus sending you to the logged out screen.

I will close this issue so we can track bugs and issues with the core codebase, but would be happy to continue to help. I would start with trying to override the built-in refresh endpoint to work with your custom auth strategy.

jmikrut commented 5 months ago

Oh also, I would expect that issue with generate:types is caused by your import here:

import { getFieldsToSign } from '~/node_modules/payload/dist/auth/getFieldsToSign'

I see that you'd like to import that getFieldsToSign function, so I will export that properly for you so you can import it properly as import { getFieldsToSign } from 'payload/auth'.

That will be released in the next beta!

Livog commented 5 months ago

@jmikrut Thank you so much James for that feedback, I will dig into that and hit you up on Discord if I run in to problems.