via postman i can login and get responses like expected, but when trying to fetch the /Me endpoint from my front-end, i always get { users : none } back, even if called directly after passing login. when i try to logout i get a "no user" error.
i have seen
credentials : 'include'
i tried adding it to the request but i get cors errors even though both urls (localhost with ports) are whitelisted
does anyone have an idea what i am doing wrong here?
To make authentication work across domains you need to set cors, csrf, and the cookie domain. Our official auth example demonstrates this pretty simply, check it out;
https://github.com/payloadcms/payload/tree/master/examples/auth/cms#readme
The
credentials: include
line in your front-end fetch will automatically attach Payload's http-only cookie to the request, but Payload will only respect that request and cookie if the settings are configured.
If you're still seeing a cors error after setting the config, double check that the values are correct. You may be using environment variables that are not loaded. This has tripped me up more times than I'm willing to admit.
Also note that Postman will not trigger cors errors because it makes the request server-side and cors is a browser-only concept.
thanks for the quick response!
the cookie domain i had not set but the cors and csrf configs are like in the example with the exception of using strings directly
const clientUrls = ['http://localhost:5173', 'http://localhost:3000'];
export default buildConfig({
serverURL: process.env.PAYLOAD_PUBLIC_SERVER_URL,
admin: {
user: Admins.slug,
},
cors: clientUrls,
csrf: clientUrls,
collections: [Admins, players],
typescript: {
outputFile: path.resolve(__dirname, "payload-types.ts"),
},
graphQL: {
schemaOutputFile: path.resolve(__dirname, "generated-schema.graphql"),
},
});
the cors errors persists
Can you paste the error here? And possibly your request as well.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/api/players/login. (Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’).
https://i.imgur.com/0F5TVjw.png
const res = await fetch('http://localhost:3000/api/players/login', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: username,
password: password,
}),
});
Weird, your response headers indicate that
http://localhost:5173
is whitelisted as expected
http://localhost:5173
is the address of your front-end right?
Yes
Are you able to hit any other endpoints with success? Like
/api/players
?
when i leave out the credentials : 'include'
i can log in , get the correct user info and token
but in the same function, after the user token retrieval, when fetching /me again, it shows not logged in, when using not the credential line (it goes through) but with the line, the cors errors appear
so nothing with the credential line included goes through, everything without goes through, works but as expected when your not logged in
Ok this is making more sense
The reason you are logging in the first time with success, but do not remain logged in, is because of the cookie domain settings
You need to whitelist
localhost
as seen here:
https://github.com/payloadcms/payload/blob/master/examples/auth/cms/src/collections/Users.ts#L14
This will allow Payload to attach the http-only cookie to your browser and read it back on every
/me
request
i tried swapping secure to false since it did not work the first time i tried, ignore that pls
Can you verify your cookie settings by inspecting the cookie in your browser?
In Chrome, Inspector > Application > Cookies
You can see what domain, etc is being attached
hmm might need to swap browsers here 😄
nothing appears there but just to be clear , i cannot log in with 'credentials : "include"' right
Right and that is because
credentials: include
attaches that cookie to the request
But all signs are pointing to a bad cookie
yea , that seems to be missing , there is nothing i have specifically do right?
im not experienced at all with web development to be honest, sorry if im being stupid here, usually doing more c++ or gamedev stuff ^^
It's all good! Happy to help. I think we're close.
Do you have any custom hooks that might be manipulating the user in the response?
there are some hooks, but they dont do anything as far as i can tell
https://i.imgur.com/U98Gm0Y.png
https://i.imgur.com/fpgHnuz.png
Try commenting those out temporarily
no effect
what about
app.use(payload.authenticate);
? i seen it somewhere, had commented it out bc it did not seem to be required
https://i.imgur.com/Pn3ThPS.png
here is a login response btw
maybe there is some useful info
@Nog can you paste what your most recent Players auth config looks like?
i was able to fix this issue 20 min ago , the essential parts i was missing was setting cookie settings in the user collection, jacob pointed that out, and lastly correctly setting the cookie.
Amazing, happy to hear it 👍
@jacobsfletch Do you know why
https://payloadcms.com/docs/authentication/using-middlewareadding an express route, req.user is always undefined
Can confirm im including credentials in the request
also, the docs mention payload.authenticate as middleware, but it always returns undefined
What do your custom Express routes look like? Here's a common setup using Payload authentication middleware with cors:
app.options('/your-route', cors);
app.post('/your-route', [
payload.authenticate,
express.json({}),
cors,
doSomething,
]);
You might also just want to use the
endpoints
config which does the same thing behind a nice API, check it out:
https://payloadcms.com/docs/rest-api/overview#custom-endpoints
It's also possible that you're calling the authentication middleware
beforeinitializing Payload. More details here
https://github.com/payloadcms/payload/issues/2327Star
Discord
online
Get help straight from the Payload team with an Enterprise License.