fastify / fastify/help

Help on @fastify/oauth2: Invalid State

Open
#1,028 0 comments 0 reactions 0 assignees View on GitHub
help wanted
Dominant language
No language data
Stars
68
Forks
8
Avg merge
11h 2m
Merged PRs (30d)
2

Description

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:

```js
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:

```js
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:

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

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

return Login with Google;
}
```

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?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.