atinux / nuxt-auth-utils

Add Authentication to Nuxt applications with secured & sealed cookies sessions.
MIT License
980 stars 91 forks source link

Oauth (Google) fail due to `400 Bad Request` in Cloudflare with `cloudflare-module` preset #284

Closed ymansurozer closed 1 week ago

ymansurozer commented 1 week ago

Hi!

I've built a very simple auth with Google provider. It works fine if I build and preview with a node server Nitro preset but if I build with the cloudflare-module present and preview via wrangler with wrangler dev, it does not work. Here is what happens:

When I input my Google credentials and continue, it redirects to the app with the appropriate code in the query but I get a internal server error and wrangler logs show a [nuxt] [request error] [unhandled] [400] [POST] "https://oauth2.googleapis.com/token": 400 Bad Request error.

My authorized redirect URI's have http://localhost:3000/auth/google configured and again, it works in a node build.

server/routes/auth/google.ts

/* eslint-disable ts/no-unsafe-member-access */
export default defineOAuthGoogleEventHandler({
  async onSuccess(event, { user }) {
    const data = {
      id: "test",
      email: user.email as string,
      name: user.name as string || undefined,
      image: user.picture as string || undefined,
    };
    await setUserSession(event, { user: data });

    const redirectUrl = getCookie(event, "redirectUrl");
    return sendRedirect(event, redirectUrl || "/app/user");
  },

  async onError(_, error) {
    throw createError({
      statusCode: error.statusCode,
      statusMessage: error.message || error.statusMessage,
    });
  },
});

nuxt.config.ts

...
  nitro: {
    preset: "cloudflare-module",
  },
...

wrangler.toml

# :schema node_modules/wrangler/config-schema.json
name = "saas-starter-cf"
compatibility_date = "2024-11-13"
main = "./.output/server/index.mjs"
assets = { directory = "./.output/public/", binding = "ASSETS" }

[observability]
enabled = true

I'm on 0.5.3 version.

ymansurozer commented 1 week ago

Okay, this one was one me, I guess. 🤷🏽 This was the solution:

image

Apparently, if you define routes in the wrangler config, it will somehow be used in the requests, hence the callback was not working. Once I deleted it, all worked fine.