【问题标题】:Google authentication in firebase showing blank screen Progressive Web AppFirebase 中的 Google 身份验证显示空白屏幕 Progressive Web App
【发布时间】:2018-03-16 04:03:14
【问题描述】:

我正在创建我的第一个 Progressive Web 应用程序,它使用 firebase 来存储数据。我还使用Gmail 作为所有将使用该应用程序的用户的入口点。但是我坚持实现登录。以下是我的登录代码:

html:

<button md-raised-button color="warn" (click)="logInGoogle()"><md-icon>group</md-icon>Sign in with google to enjoy the app</button> 

ts:

logInGoogle(){
    this.authService.loginWithGoogle().then( user => {
      console.log("User is logged in");
      //this.router.navigate(['/addweather']);
    })
    .catch( err => {
      console.log('some error occured');
    })
  }

这里是服务:

loginWithGoogle() {
    return this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
  }

还要检查auth 状态,我在app.component.ts 构造函数中有这个:

this.authService.afAuth.authState.subscribe(
      (auth) => {
        if(auth === null){
          console.log("Not Logged in.");
          this.router.navigate(['login']);
          this.isLoggedIn = false;
        }
        else {
          console.log("Successfully Logged in.");
          this.isLoggedIn = true;
          this.router.navigate(['']);
        }
      }
    )

现在应用程序显示了一些行为:

  1. 此登录功能在浏览器上运行良好,因为如果我单击登录按钮,它会打开一个新窗口、授权我并返回到打开应用程序的同一选项卡。

    李>
  2. 当我将应用程序添加到主屏幕并尝试再次登录时,它会提示我输入以下选项:

单击 chrome 后,它会授权我并将我重定向到应用程序,但应用程序现在显示一个空白屏幕,并且 oAuth 屏幕只是进入无限处理状态。 为什么会发生这种情况?我的意思是它不应该像在浏览器中运行应用程序时那样正常工作。

同样在点击登录按钮时,它不应该提示如上图所示的选项;相反,它应该打开一个 oAuth 对话框。我也尝试使用以下代码执行此操作:

logInGoogle(){
    var newWindow = window.open('https://accounts.google.com/o/oauth2/auth?scope=https://www.google.com/m8/feeds&client_id=9722-j3fstr5sh6pumie.apps.googleusercontent.com&redirect_uri=https://weatherapp321.firebaseapp.com/__/auth/handler&response_type=token', 'name', 'height=600,width=450');

  }

现在这会打开一个所需的对话框,而不是提示选项。但是在授权之后,这让我回到了登录页面。 为什么会发生这种情况?当我已经在检查 app.component.ts 中的身份验证状态并在用户获得授权时将用户重定向到主页时。

感谢您耐心阅读到最后。非常感谢您的帮助。

编辑

正如叶夫根所建议的: 尝试使用signInWithRedirect。当我第一次登录时它工作了,有 2 秒的轻微延迟。但是后来我退出了,又想重新登录,登录后就黑屏了。

【问题讨论】:

    标签: angular firebase firebase-authentication progressive-web-apps


    【解决方案1】:

    看起来您的应用在移动设备上打开的身份验证不是当前浏览器的新选项卡,而是在新浏览器中,因此在通过 Google 进行身份验证后,它无法有效地重定向回您的初始浏览器。如果您使用重定向登录,您将停留在同一个浏览器中,因此您需要将服务更改为:

    loginWithGoogle() {
        return this.afAuth.auth.signInWithRedirect(new firebase.auth.GoogleAuthProvider());
    }
    

    【讨论】:

    • 当用户未登录但延迟 3 秒时,它第一次使用 signInWithRedirect 确实有效。而且,如果我注销然后再次尝试登录,应用程序会登录我,但随后会显示一个空白屏幕。
    • 如果你愿意,我可以分享网址,然后你可以在移动设备上试用。
    【解决方案2】:

    我的宠物网络应用程序的行为几乎相同。 对于我自己,我通过以下步骤解决它:

    1. 我将 firebase 初始化移至 app.module.ts

    @NgModule({
        ...
        providers: [
            { provide: APP_INITIALIZER, useFactory: appConfig, deps: [AuthService], multi: true }
        ]
    })
    
    export function appConfig(authService) {
        const app = firebase.initializeApp({
            apiKey
            authDomain
        });
        return () => new Promise((resolve, reject) => {
            firebase.auth()
            .onAuthStateChanged(data => {
                if (data) {
                  firebase.auth().currentUser.getToken()
                    .then((token: string) => authService.setToken(token););
                }
                resolve(true);
            }, error => resolve(true));
        });
    }
    1. 重定向到我在auth.guard.ts 管理的登录页面

    export class AuthGuard implements CanActivate {
        constructor(
            private authService: AuthService,
            private router: Router
        ) {}
    
        canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
            if (this.authService.isAuthenticated()) {
                return true;
            } else {
                this.router.navigate(['/signin']);
                return false;
            }
        }
    }
    1. 我的auth.service.ts 中有下一个代码

    export class AuthService {
        token: string;
    
        signinUser(email: string, password: string) {
            return new Promise((resolve, reject) => {
                firebase.auth().signInWithEmailAndPassword(email, password)
                    .then(resp => {
                        firebase.auth().currentUser.getToken()
                            .then((token: string) => {
                                this.token = token;
                                resolve(resp);
                            }).catch(reject);
                        return resp;
                    })
                    .catch(reject);
                });
        }
    
        signoutUser() {
            return firebase.auth().signOut()
                .then(resp => this.token = null);
        }
    
        getToken() {
            firebase.auth().currentUser.getToken()
                .then((token: string) => this.setToken(token));
            return this.token;
        }
        
        setToken(token) {
          this.token = token;
        }
    
        isAuthenticated() {
            return this.token != null;
        }
    }

    希望对你有帮助。

    【讨论】:

    • 我尝试了你所有的步骤,但仍然得到相同的行为。在浏览器上运行良好,但在移动设备上不行。
    【解决方案3】:

    redirect auth 不适用于 PWA(在某些情况下可能使用不同的浏览器实例)。您可以使用 pop-up auth 流程解决此问题:

    https://firebase.google.com/docs/auth/web/google-signin

    看起来像这样:

    firebase.auth().signInWithPopup(provider).then(function(result) {
      // This gives you a Google Access Token. You can use it to access the Google API.
      var token = result.credential.accessToken;
      // The signed-in user info.
      var user = result.user;
      // ...
    }).catch(function(error) {
      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;
      // The email of the user's account used.
      var email = error.email;
      // The firebase.auth.AuthCredential type that was used.
      var credential = error.credential;
      // ...
    });
    

    唯一的流程不同是它启动一个弹出浏览器窗口,而不是重定向当前实例。这也简化了获取身份验证结果的一些逻辑。如果您希望在非 PWA 上保持正常流程,您可以检测应用是否从主屏幕启动:

    https://developers.google.com/web/updates/2015/10/display-mode

    【讨论】:

      【解决方案4】:

      我遇到了同样的问题,this 为我工作,如果我能提供帮助,请告诉我。

      【讨论】:

        猜你喜欢
        • 2015-01-26
        • 1970-01-01
        • 2011-12-05
        • 2019-03-20
        • 2022-07-11
        • 2021-10-31
        • 2015-09-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多