atinux / nuxt-auth-utils

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

Session information not avaliable on front when using firebase functions #190

Open ralacerda opened 1 month ago

ralacerda commented 1 month ago

Hello. I'm trying to use this module with Nuxt and Firebase but I'm having a few problems.

I'm using firebase function and Google OAuth. I had to set the NUXT_OAUTH_GOOGLE_REDIRECT_URL, otherwise the redirect url would be the firebase function url.

For the backend part, everything is okay, I get authentication success and I can set the values for the session. But in my frontend, when using useUserSession() I get an empty session and loggedIn is false. The nuxt-session cookie is present, but the front can't read it.

I already tried turning SSR on and off. Even when SSR is on, the HTML generated by the server doesn't include the user session.

Now, if I call my API and use await getUserSession(event), it works and I can recover the user info.

I'm using version 0.3.9 and I also tried 0.3.4 with no success (I can't go to lower version because I need the redirect_url feature.

Any help debugging the problem will be appreciated.

atinux commented 1 month ago

What happens when you go on /api/_auth/session with your browser once the cookie is set?

ralacerda commented 1 month ago

I get a 200 response but an empty value.

ralacerda commented 1 month ago

I solved part of the problem. I believe because I misconfigured the OAuth earlier, there was a cookie set for the firebase function url. After clearing that, I'm back to auth not working in any context.

So the problem is most likely that I'm not able to set the user session to the website url. Is there a way to decrypt the cookie so I can check if it's valid?

atinux commented 1 month ago

You can overwrite the cookie domain this way:

export default defineNuxtConfig({
  $production: {
    runtimeConfig: {
      session: {
        cookie: {
          domain: 'example.com'
        }
      }
  }
})
ralacerda commented 1 month ago

Should exemple.com but the hosting url or the firebase function url? I tried both to no avail. I'm also getting a typescript error that domain is not a property of cookie.

MasterCarl commented 1 month ago

Are you using Safari, by any chance? I spent a few hours debugging an empty response from useUserSession after a successful authentication flow.

Eventually, I noticed that everything did work fine in Chrome. I was able to also get it to work locally in Safari by setting

runtimeConfig: {
    session: {
      cookie: {
        secure: !import.meta.dev,
      },
    },
  },

in nuxt.config.ts.