You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt.js应用中Firebase Apple登录使用signInWithRedirect时getRedirectResult始终返回null的解决求助

Nuxt.js应用中Firebase Apple登录使用signInWithRedirect时getRedirectResult始终返回null的解决求助

大家好,我目前在做一个基于Nuxt.js(Vue.js)+ Firebase的项目,Firebase的Apple登录用signInWithPopup是完全正常的,自定义域名也已经在Auth设置里配置好了,但换成signInWithRedirect就出问题了:

流程是这样的:点击“Sign in with Apple”按钮触发登录函数,能正常跳转到Apple的登录页面,输入凭据后也能跳回我的登录页,但完全没有任何反应,既没有错误提示,getRedirectResult返回的结果还一直是null。我试过把getRedirectResult的代码移到onMounted里,情况也没有改善。

下面是我的实现代码,麻烦各位帮忙看看哪里出问题了,怎么才能让getRedirectResult正确获取到登录结果?

<script setup lang="ts">
// Define page meta to use appropriate layout
definePageMeta({ layout: 'web-no-tab-bar' });
useSeoMeta({ title: 'Sign-In' });

import { httpsCallable } from 'firebase/functions'
import { GoogleAuthProvider, OAuthProvider, signInWithPopup, updateProfile, getAdditionalUserInfo, signInWithRedirect, getRedirectResult, getAuth } from 'firebase/auth'
import { doc, getDoc, Firestore } from 'firebase/firestore'

// Store instances
const authStore = useAuthStore()
const flashStore = useFlashStore()

// Firebase instances
const { $auth, $firestoreDb, $functionsInstance } = useNuxtApp()
const auth = getAuth();

getRedirectResult(auth)
  .then((result) => {
    //-----------&gt; ALWAYS NULL
    // Check if result is not null before processing
    if (result) {
      alert('result')
      const credential = OAuthProvider.credentialFromResult(result);
      if (credential) {
        // You can also get the Apple OAuth Access and ID Tokens.
        const accessToken = credential.accessToken;
        const idToken = credential.idToken;
      }
      // The signed-in user info.
      const user = result.user;
    }
  })
  .catch((error) => {
    // Handle Errors here.
    const errorCode = error.code;
    const errorMessage = error.message;
    // The email of the user's account used.
    const email = error.customData.email;
    // The credential that was used.
    const credential = OAuthProvider.credentialFromError(error);
    // ...
  });

/**
 * ================================
 * Apple Sign-In
 * ================================
 */
const signInWithApple = async () => {
  try {
    const provider = new OAuthProvider('apple.com')
    // Configure Apple provider with required scopes
    provider.addScope('email')
    provider.addScope('name')
    const result = await signInWithRedirect($auth, provider)
  } catch (err: any) {
    // eslint-disable-next-line no-console
    console.error('Apple sign-in failed:', err)
    flashStore.show(err?.message || 'Apple sign-in failed. Please try again.')
  }
}

/**
 * ================================
 * Providers Sign-In
 * ================================
 */
// Verify user profile after authentication. Not for email sign-in. For providers.
const checkUserProfileAfterProvidersSignIn = async (userId: string) => {
  try {
    const userDoc = await getDoc(doc($firestoreDb as Firestore, 'users', userId))
    // If missing username or country, treat as new user
    if (!userDoc.exists() || !userDoc.data()?.username || !userDoc.data()?.country) {
      navigateTo('/authentication/user-info-collect')
    } else {
      // Persist user country in localStorage for later use
      if (utils.isLocalStorageAvailable()) {
        const key = `selectedCountry_${userId}`
        window.localStorage.setItem(key, userDoc.data()?.country.toLowerCase())
      }
      // Redirect back to the page the visitor came from (or home)
      const target = utils.isLocalStorageAvailable() ? window.localStorage.getItem('previousUrlForAfterSignIn') || '/' : '/'
      navigateTo(target)
    }
  } catch (err) {
    // eslint-disable-next-line no-console
    console.error('Error verifying user profile after Google sign-in:', err)
    navigateTo('/')
  }
}

// Store previous URL in localStorage for future redirect handling
onMounted(() => {
  if (utils.isLocalStorageAvailable()) {
    const previousUrl = (window.history.state && window.history.state.back) || document.referrer || '/';
    localStorage.setItem('previousUrlForAfterSignIn', previousUrl);
  }
});
</script>

我自己尝试过的排查方向:

  • 确认了Firebase Auth的自定义域名配置正确,signInWithPopup能正常工作也证明了这一点
  • 将getRedirectResult的调用移到onMounted钩子内,结果还是null
  • 检查了Apple Developer后台的回调URL配置,和Firebase里的一致

有没有朋友遇到过类似的问题?或者能帮我指出代码里可能忽略的点?

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 10:12:59