Firebase中的Google身份验证显示空白屏幕Progressive Web App [英] Google authentication in firebase showing blank screen Progressive Web App

查看:94
本文介绍了Firebase中的Google身份验证显示空白屏幕Progressive Web App的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建自己的第一个渐进式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. 如果我单击登录按钮,它会打开一个新窗口,授权我并返回到打开该应用程序的同一选项卡,则该登录功能在浏览器上效果很好,因为. li>

  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中检查auth状态并在用户获得授权时将用户重定向到主页时.

感谢您的耐心和阅读,直到结束.帮助将不胜感激.

修改

根据叶夫根(Yevgen)的建议: 尝试过signInWithRedirect.当我第一次登录时稍有延迟2秒,它就起作用了.但是后来我注销并尝试再次登录,登录后出现黑屏.

解决方案

我在宠物Web应用程序上的行为几乎相同. 对于我自己,我可以通过以下步骤解决此问题:

  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
  2. 中管理的LoginPage

 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
  2. 中有下一个代码

 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;
    }
} 

希望对您有所帮助.

I am on the way to create my first Progressive web app which uses firebase for storing data. I am also using Gmail as an entry point for all the users that would use the app. However I am stuck on implementing login. Below is my the code for logging in:

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');
    })
  }

Here's the service:

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

Also to check the auth state I have this in my app.component.ts constructor:

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(['']);
        }
      }
    )

Now there are a couple of behaviors that the app is showing :

  1. This login functionality works fine on browsers coz if i click on the login button it opens up a new window, authorizes me and comes back to the same tab on which the app is opened.

  2. When I add the app to the home screen and try to login again it prompt me for below options:

Once I click on chrome, it authorizes me and redirects me to the app but the app shows a blank screen now and the oAuth screen just goes on an infinite processing state. Why is this happening? I mean shouldn't it just work the normal way as it worked when the app was run in browser.

Also on clicking the login button it shouldn't prompt the option as shown in the above image; instead it should open an oAuth dialog. I tried doing this also with the following code:

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');

  }

This now instead of prompting with the options opens up a dialog which is desired. But after authorizing, this lands me back to the login page. Why is this happening? when I am already checking the auth state in app.component.ts and redirecting the user to home page if the user gets authorized.

Thanks for being patient and reading till the end. Help would be much appreciated.

Edit

As suggested by Yevgen: Tried with signInWithRedirect. It worked when I first logged in with a slight delay of 2 seconds. But then I logged out and tried to log in again, I get a blank screen after getting logged in.

解决方案

I had almost same behavior on my pet web app. For my self I solve it by the next steps:

  1. I move firebase initialization to the 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. Redirection to LoginPage I managed in 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. I had the next code in my 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;
    }
}

I hope it will be helpful for you.

这篇关于Firebase中的Google身份验证显示空白屏幕Progressive Web App的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆