Flutter Web:Safari Google登录第一次尝试被阻止



我正在开发一个Flutter Web应用程序,该应用程序使用谷歌登录和Firebase身份验证。目前,谷歌登录在大多数浏览器上运行完全正常。不过,我注意到,当在弹出窗口被阻止的情况下在iPhone上使用Safari时,第一次身份验证失败,它不起作用(什么都不会出现(。弹出窗口似乎被阻止了。不过,通过在之后立即点击按钮,身份验证就成功了。

Safari中的第一次交互根本不起作用,即使在Firefox或Chrome中也会起作用。我还注意到谷歌登录方法在私人(匿名(浏览器中不起作用。

这是我当前的googleSignIn((方法:

static Future<void> signInWithGoogle() async {
try {
final GoogleSignIn googleSignIn = GoogleSignIn();
final GoogleSignInAccount? googleSignInAccount =
await googleSignIn.signIn();
if (googleSignInAccount != null) {
final GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
await FirebaseAuth.instance.signInWithCredential(credential);
}
} catch (error) {
throw error;
}

}

如上所述,它在我测试过的所有其他浏览器中都运行良好。当弹出窗口没有被阻止时,它也可以在Safari中工作,尽管在第一次调用时,它会询问用户是否希望允许弹出窗口。

我想指出的是,其他使用谷歌登录的网站并没有遇到同样的问题,这似乎是Flutter的谷歌登录包特有的。

在搜索GitHub和StackOverflow后,我找到了解决方案。在应用程序初始屏幕的initState中,调用GoogleSignIn().signInSilently()。这不是谷歌有意的功能,而是一个令人愉快的bug解决方法。

有关更多上下文,请参阅Google自己的Google_sign_in示例。一定要关注initState

最后,如果您在使用Firebase身份验证和Google登录,这里有一种方法可以捕获silentSignIn()生成的用户对象,这样您就可以获得好处。

static Future<void> signInWithGoogleSilently() async {
try {
final GoogleSignIn googleSignIn = GoogleSignIn();
final GoogleSignInAccount? googleSignInAccount =
await googleSignIn.signInSilently();
if (googleSignInAccount != null) {
final GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
await FirebaseAuth.instance.signInWithCredential(credential);
}
} catch (error) {
throw error;
}
}

相关内容

最新更新