Skip to content

Failed to exchange the Google token #324

Open
@adnanerlansyah403

Description

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, '/')
    },
})

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions