iT邦幫忙

2

[IONIC 4 + Firebase教學] Authentication 身分驗證

Firebase 提供了簡單的Authentication,讓開發者不需要自己Server端開發身分驗證的機制. Firebase 提供了Email/Password, Google, Facebook, Twitter等等的登入機制, 這篇主要是介紹如何在IONIC 使用Firebase Email/Password功能.

首先導入模組import { AngularFireAuth } from '@angular/fire/auth';.我通常會有AuthService, 分別有 register,login, signout 方法.

register(email:string, password:string){
    return this.afAuth.auth.createUserWithEmailAndPassword(email,password);
  }

方法createUserWithEmailAndPassword會回傳一個Promise, 成功後就切換到 Login頁面.

 this.authService.register(this.user.email, this.user.password).then((res: any) => {
        this.router.navigateByUrl('path');
      })
      .catch((error: any) => console.error(error));

在login方法裡使用方法如下,一樣會回傳一個Promise.

this.afAuth.auth.signInWithEmailAndPassword(email, password)

在成功會傳Response, 我用Subject去通知有訂閱這個Subject的Function,去做login後的頁面呈現.

//宣告一個Subject
public authSubject = new Subject<boolean>();
....//更新Subject的值,並做通知
 this.authSubject.next(true);
 ....//任何訂閱這個subject都可以取得現在Authentication的狀態.
 this.authService.authSubject.subscribe((isAuth)=>{
      this.isAuth = isAuth;
    });

因為登入後user會暫存在Memory,下次使用App始就不需要在登入, 如何讓App知道暫存的user, 我們可以使用如下的方法,同樣的使用authSubject去通知App.

this.afAuth.auth.onAuthStateChanged((user: firebase.User)=>{
      if(user){
        this.authSubject.next(true);
        console.log('user found');
      }else{
        this.authSubject.next(false);
        console.log('user not found');
        this.router.navigate(['tabs/login']);
      }
    });

signout 非常簡單

 this.afAuth.auth.signOut().then(function() {
      console.log('Logout Succcess!');
      this.router.navigateByUrl('tabs/login');
    }).catch(function(error) {
     console.log(error);
    });

以上是我用Firebase 身分驗證機制,如果有任何錯誤或是補充,歡迎回覆!/images/emoticon/emoticon29.gif


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言