oauth2.0 如何在+page.server.js中设置cookie并在+server.js中访问它

laawzig2  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(147)

我有一个问题与上述问题.我试图使用谷歌oauth认证,但是我被“预期的状态和验证器”不匹配“返回的状态和验证器从谷歌。"问题是在发送请求到谷歌提供商重定向之前,我设置了状态和验证器为cookie。这是从/signup/+ page. server. js完成的,我试图访问的是从/API/oauth/google/+ server.js和我得到的状态和验证器是未定义的

我的+page.server.js操作:

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);
    }

字符串

在我的+server.js中,我做了这样的事情:

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);


..........


我得到这个错误:
expectedState未定义
expectedVerifier未定义
状态e2 LyMU 4 i1 lTSGbBEDyWuBKnp 8 F3 zJG
代码4/0AfJohXke 3dhNwRBhew 7 jMA 1_Aj 5 KuxuiitAeVh 4Vn 6 g7 oZy 6V 5DR 9 f8 PqxM-llh 8_fVs 8 g
状态不匹配未定义e2 LyMU 4 i1 lTSGbBEDyWuBKnp 8 F3 zJG
我试着将状态设置为 event.locals.stateevent.locals.verifier 而不是cookie,但仍然是同样的问题。当我到达+server.js时,我选择了event.locals,它是undefined
我希望从我的+page.server.js到我的+server.js的验证器和状态。然后我可以考虑如何安全地完成它。最好两者都有

aiazj4mn

aiazj4mn1#

你很可能有一个句柄钩子在运行,它覆盖了cookie。例如,如果你在hooks.server.js中有这样的东西:

response.headers.set('set-cookie', cookie);

字符串
它将覆盖在+page.server.js中设置的cookie
相反,您可以使用headers.append来附加cookie:

response.headers.append('set-cookie', cookie);

相关问题