Skip to content

Help on @fastify/oauth2: Invalid State #1028

@fberrez

Description

@fberrez

TL;DR

My authentication on google works when I go on my backend http://localhost:3000/login/google. It does not work through my frontend that performs this redirection: http://localhost:5173/login/google -> http://localhost:3000/login/google.


My backend is running on :3000. Here is my configuration for oauth2 google:

import Fastify from 'fastify';
import oauthPlugin from '@fastify/oauth2';

const fastify = Fastify();

fastify.register(oauthPlugin, {
  name: 'googleOAuth2',
  scope: ['email'],
  credentials: {
    client: {
      id: config.get('authentication.google.clientId'),
      secret: config.get('authentication.google.clientSecret'),
    },
    auth: oauthPlugin.GOOGLE_CONFIGURATION,
  },
  startRedirectPath: '/login/google',
  callbackUri: 'http://localhost:3000/login/google/callback',
});

Here is my callback controller:

static async callback(req, reply, instance) {
    instance.googleOAuth2.getAccessTokenFromAuthorizationCodeFlow(
      req,
      async (err, result) => {
        if (err) {
          reply.send(err);
          return;
        }
       ...
      });
}

When I open my browser and I go on http://localhost:3000/login/google, everything works fine: my callback controller has err = null.

So now, I have this react project with this simple component:

// http://localhost:5173/login/google
import { Button } from '../ui/button';

export function LoginButtonGoogle() {
  const handleLogin = () => {
    window.location.href = `http://localhost:3000/login/google`;
  };

  return <Button onClick={handleLogin}>Login with Google</Button>;
}

I'm redirected to the google authentication page. But when it goes back to my callback controller, err = Invalid State.

I don't understand why because it is juste a redirection performed on my frontend page without adding any other parameter.

Do you have any idea?

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedExtra attention is needed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions