im having a problem with the issue above. i am trying to use google oauth to authenticate, but i get stumped with that the "expected state and verifier" dont match the "returned state and verifier from google.". the problem is before sending the request to google provider redirect i set the sate and verifier to cookies. this is done from /signup/+page.server.js the i try to access is from /api/oauth/google/+server.js and i get that the state and verifier are undefined
my +page.server.js action:
oauth2google: async (event) => {
const authMethods = await event.locals.pb?.collection('users_valiantlynx').listAuthMethods(); // generates a state and a verifier
if (!authMethods) {
return {
authProviders: ''
};
}
const redirectUrl = `${event.url.origin}/api/oauth/google`;
const googleAuthProvider = authMethods.authProviders.find((provider) => provider.name === 'google');
const authProviderRedirect = `${googleAuthProvider?.authUrl}${redirectUrl}`;
console.log('googleAuthProvider', event);
// Save the state and verifier in a cookie
const state = googleAuthProvider.state;
const verifier = googleAuthProvider.codeVerifier;
console.log('state', state);
console.log('verifier', verifier);
event.cookies.set('googleAuthState', state);
event.cookies.set('googleAuthVerifier', verifier);
throw redirect(302, authProviderRedirect);
}
in my +server.js i do something like:
export const GET = async ({ locals, url, cookies }) => {
console.log('GET', cookies.getAll());
const redirectUrl = `${url.origin}/api/oauth/google`;
const expectedState = cookies.get('googleAuthState');
const expectedVerifier = cookies.get('googleAuthVerifier'); //! everytime the listAuthMethods is called, the verifier changes. so we cant get the verifier pocketbase function hook. cause it will be different from the one we saved in the cookie from the action hook
console.log('expectedState', expectedState);
console.log('expectedVerifier', expectedVerifier);
const state = url.searchParams.get('state');
const code = url.searchParams.get('code');
console.log('state', state);
console.log('code', code);
..........
i get this error:
expectedState undefined
expectedVerifier undefined
state e2LyMU4i1lTSGbBEDyWuBKnp8F3zJG
code 4/0AfJohXke3dhNwRBhew7jMA1_Aj5KuxuiitAeVh4Vn6g7oZy6V5DR9f8PqxM-llh8_fVs8g
state mismatch undefined e2LyMU4i1lTSGbBEDyWuBKnp8F3zJG
ive tried setting the state to the event.locals.state and event.locals.verifier intead of a cookie but it was still the same issue. when i got to +server.js i chect the event.locals and it was undefined.
im expecting to get the verifier and the state from my +page.server.js to my +server.js at all. then i can consider how to do it safely. preferably both
You most likely have a handle hook running that overrides the cookies. For example, if you have something like this in your hooks.server.js:
it will override the cookies set in +page.server.js
Instead you can use
headers.append
to append the cookies: