Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Failed to exchange the Google token #324

Open
adnanerlansyah403 opened this issue Jan 17, 2025 · 0 comments
Open

Failed to exchange the Google token #324

adnanerlansyah403 opened this issue Jan 17, 2025 · 0 comments

Comments

@adnanerlansyah403
Copy link

Hello everyone, has anyone here ever encountered the error that the code from Google OAuth is not valid when I try to exchange it for a token from the backend? I followed this article to implement a login flow with Google using nuxt-utils, but when the code is sent to the backend, it becomes invalid, resulting in the error: failed to exchange Google token

Guide to using OAuth 2.0 to access Google APIs

This is my code to handle login google oauth.

// @ts-nocheck
export default defineOAuthGoogleEventHandler({
    config: {
        authorizationURL: 'https://accounts.google.com/o/oauth2/auth',
        tokenURL: 'https://oauth2.googleapis.com/token',
        userURL: 'https://www.googleapis.com/oauth2/v3/userinfo',
        authorizationParams: {
          scope: 'email profile openid'
        },
    },
    // @ts-ignore
    async onSuccess(event) {
        const query = await getQuery(event);
        const code = query.code; // This code isn't valid when I sent to backend 
    
        console.log(query)
        // Check if the data user is matched from the database
        // If it's matched then then make user login else redirect user to register page
        // Construct a script to close the popup and notify the parent
        const closeScript = `
            <script>
                if (window.opener) {
                    window.opener.postMessage({ success: true, code: '${code}' },  '*');
                    window.close();
                }
            </script>
        `;

        // Return a response that runs the script
        // return sendRedirect(event, '/auth/register')
        return send(event, closeScript, 'text/html');
    },
    onError(event, error) {
        console.error('Google OAuth error:', error);
        // You can choose to send an error response instead of redirecting
        return sendRedirect(event, '/')
    },
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant