Search code examples
javascriptfirebasenuxt.jsfirebase-app-checkvuefire

How to use Nuxt VueFire Session Cookie with App Check and browser key restrictions?


I am trying to implement Nuxt VueFire with Session Cookie as per the docs.

This is my runtimeConfig andvuefire config objects in nuxt.config.ts:

  runtimeConfig: {
    public: {
      // Nuxt auto replaces values with matching .env values prefixed with NUXT_PUBLIC
      brandName: "",
      fbApiKey: "",
      fbAuthDomain: "",
      projectId: "",
      fbDefaultStorageBucket: "",
      fbMessagingSenderId: "",
      fbAppId: "",
      fbMeasurementId: "",
      gcpRecaptchaEnterpriseSiteKey: "",
    },
  },
  vuefire: {
    config: {
      apiKey: process.env.NUXT_PUBLIC_FB_API_KEY,
      authDomain: process.env.NUXT_PUBLIC_FB_AUTH_DOMAIN,
      projectId: process.env.NUXT_PUBLIC_PROJECT_ID,
      storageBucket: process.env.NUXT_PUBLIC_FB_DEFAULT_STORAGE_BUCKET,
      messagingSenderId: process.env.NUXT_PUBLIC_FB_MESSAGING_SENDER_ID,
      appId: process.env.NUXT_PUBLIC_FB_APP_ID,
      measurementId: process.env.NUXT_PUBLIC_FB_MEASUREMENT_ID,
    },
    auth: {
      enabled: true,
      sessionCookie: true,
    },
    appCheck: {
      // Allows you to use a debug token in development
      debug: process.env.NODE_ENV !== "production",
      isTokenAutoRefreshEnabled: true,
      provider: "ReCaptchaEnterprise",
      key: process.env.NUXT_PUBLIC_GCP_RECAPTCHA_ENTERPRISE_SITE_KEY || "none",
    },
  },

But when using App Check with Session Cookie it throws the below error. It works fine when I remove sessionCookie: true so this error is definitely related to Session Cookie + App Check together.

I think this error arises because the debug token used for Firebase App Check is typically available only in the client-side environment. When sessionCookie is enabled, the server attempts to authenticate the token, which isn't available or valid in the server context.

Here is the error I am seeing on screen (not in the console) when App Check and sessionCookie: true are enabled together:

500
Firebase: Error (auth/firebase-app-check-token-is-invalid.).

at _fail (/Users/BenJackGill/Dev/seoturbo/node_modules/@firebase/auth/src/core/util/assert.ts:65:9)
at _performFetchWithErrorHandling (/Users/BenJackGill/Dev/seoturbo/node_modules/@firebase/auth/src/api/index.ts:210:9)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at _performSignInRequest (/Users/BenJackGill/Dev/seoturbo/node_modules/@firebase/auth/src/api/index.ts:231:27)
at Module.signInWithCustomToken (/Users/BenJackGill/Dev/seoturbo/node_modules/@firebase/auth/src/core/strategies/custom_token.ts:56:37)
at async ./node_modules/nuxt-vuefire/dist/runtime/auth/plugin-authenticate-user.server.mjs:36:135
at async setup (./virtual:nuxt:/Users/BenJackGill/Dev/seoturbo/apps/web/.nuxt/plugins/server.mjs:58:116)
at async Object.callAsync (/Users/BenJackGill/Dev/seoturbo/node_modules/unctx/dist/index.mjs:72:16)
at async applyPlugin (/Users/BenJackGill/Dev/seoturbo/node_modules/nuxt/dist/app/nuxt.js:116:25)

Also if my Firebase Browser API Key has a website restriction set (http://localhost:3000 and http://localhost:3000) I get this error on the screen (not in the console).

I think this error is due to the Firebase API key being restricted to specific domains, and since the server does not send a referer header that matches these domains, the requests are blocked.

Here is the error I am seeing on screen (not in the console) when I have Firebase Browser API Key has a website restrictions set:

500
Firebase: Error (auth/requests-from-referer-<empty>-are-blocked.).

at _fail (/Users/BenJackGill/Dev/seoturbo/node_modules/@firebase/auth/src/core/util/assert.ts:65:9)
at _performFetchWithErrorHandling (/Users/BenJackGill/Dev/seoturbo/node_modules/@firebase/auth/src/api/index.ts:210:9)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at _performSignInRequest (/Users/BenJackGill/Dev/seoturbo/node_modules/@firebase/auth/src/api/index.ts:231:27)
at Module.signInWithCustomToken (/Users/BenJackGill/Dev/seoturbo/node_modules/@firebase/auth/src/core/strategies/custom_token.ts:56:37)
at async ./node_modules/nuxt-vuefire/dist/runtime/auth/plugin-authenticate-user.server.mjs:36:135
at async setup (./virtual:nuxt:/Users/BenJackGill/Dev/seoturbo/apps/web/.nuxt/plugins/server.mjs:58:116)
at async Object.callAsync (/Users/BenJackGill/Dev/seoturbo/node_modules/unctx/dist/index.mjs:72:16)
at async applyPlugin (/Users/BenJackGill/Dev/seoturbo/node_modules/nuxt/dist/app/nuxt.js:116:25)

I think it might be related to my auth middleware, which triggers calls on the server sometimes, so I will include that here also. Note I tried excluding it from running on the server as shown in docs here and in the comments below, but it had no effect:

// middleware/auth.ts
export default defineNuxtRouteMiddleware(async (to, from) => {
  // I tried using this to skip middleware on initial client load. It does not work.
  // const nuxtApp = useNuxtApp();
  // if (
  //   import.meta.client &&
  //   nuxtApp.isHydrating &&
  //   nuxtApp.payload.serverRendered
  // ) {
  //   return;
  // }

  // I also tried using this to skip middleware on the server. It does not work.
  // if (import.meta.server) {
  //   return;
  // }

  // Get the current user
  const user = await getCurrentUser();

  // Redirect all logged out users login page
  if (!user) {
    return navigateTo({
      path: "/login",
    });
  }
});

How can I overcome this?


Solution

  • I tried to replicate your exact errors, but I couldn't. On configuring vuefire-nuxt, I did notice some possible causes of your error.

    Here is a link to a repo with a minimal implementation of the vuefire nuxt authentication, in this example I used google as sign-in provider

    Possible causes for your errors:

    1. Missing packages, check possible packages to add from the template project of vuefire
    2. The Firebase console configuration contains several elements that could be incorrect and result in app check errors.
    3. nuxt.config.ts I can see you'r missing the modules: ['nuxt-vuefire', '@vueuse/nuxt']
    4. Set the debug token in firebase console, the token will be available client browser console log