中安拓也のブログ

プログラミングについて書くブログ

Angular + Firebase でGoogle認証

f:id:l08084:20201004191022p:plain

はじめに

Ionic(Angular)のアプリでFirebase認証によるGoogle認証を実装します。

関連記事

メールアドレス/パスワード、Twitter、FacebookによるFirebase認証については過去に記事にしています。

  • メールアドレス/パスワードによる認証

AngularでFirebase認証(その1) Firebaseのセットアップ - 中安拓也のブログ

AngularでFirebase認証(その2) Angular Materialを使ったログイン画面の作成 - 中安拓也のブログ

AngularでFirebase認証(その3) Firebase Authentication の呼び出し - 中安拓也のブログ

Angular + Firebase でアカウント登録画面の作成 - 中安拓也のブログ

  • Twitter認証

Angular + Firebase でTwitter認証 - 中安拓也のブログ

  • Facebook認証

Angular + Firebase でFacebook認証 - 中安拓也のブログ

  • Firebase認証のリダイレクトモード

【Angular】リダイレクトモードでFirebase認証を行う - 中安拓也のブログ

環境

ハイブリットモバイルアプリ用フレームワークであるIonic(Angular)とFirebaseを使用してアプリを作成しています。

  • firebase@7.21.1

$ ionic infoコマンドの実行結果

$ ionic info

Ionic:

   Ionic CLI                     : 6.11.8 (/usr/local/lib/node_modules/@ionic/cli)
   Ionic Framework               : @ionic/angular 5.3.3
   @angular-devkit/build-angular : 0.1000.8
   @angular-devkit/schematics    : 10.0.8
   @angular/cli                  : 10.0.8
   @ionic/angular-toolkit        : 2.3.3

Capacitor:

   Capacitor CLI   : 2.4.1
   @capacitor/core : 2.4.1

Utility:

   cordova-res : not installed
   native-run  : not installed

System:

   NodeJS : v12.13.1 (/usr/local/bin/node)
   npm    : 5.6.0
   OS     : macOS Catalina

FirebaseコンソールでGoogle認証を有効にする

f:id:l08084:20201005221739p:plain
ログイン方法タブでGoogleを有効にする

  1. Firebaseコンソールで[Authentication]セクションを開きます。
  2. [ログイン方法]タブで[Google]を有効にし、[保存]をクリックします。

Googleのログインボタン作成

Step1: Googleのロゴアイコンを取得

まず、Icons8からGoogleのロゴアイコンをダウンロードします。

f:id:l08084:20201005215901p:plain
Googleのロゴ

Step2: GoogleカラーをIonicに追加

GoogleのログインボタンのカラーをIonicの配色に追加します。配色の追加方法については、下記の記事を参考にしてください。

【Ionic v5】Colorsに色を追加してボタンに適用する - 中安拓也のブログ

Step3: ログインボタンのテンプレートを作成

login.page.html

      <ion-button (click)="signInWithGoogle()" color="google" class="login-button google">
        <img class="g-icon" src="assets/icon/google-logo.png">Googleでログイン
      </ion-button>

login.page.scss

.login-button {
    font-weight: bold;
    margin-bottom: 18px;
    width: 100%;

    &.google {
        --border-style: solid;
        --border-width: 1px;
    }

    .g-icon {
        position: absolute;
        left: 15px;
        top: 25%;
        width: 1.4em;
    }
}

f:id:l08084:20201006125139p:plain
作成されたGoogleのログインボタン

Step4: リダイレクトモードでFirebase認証(Google)

モバイルデバイスによる認証を想定しているため、FirebaseのGoogle認証をリダイレクトモード(signInWithRedirect)で実装していきます。

下記のコードはFirebase認証を呼び出すサービスクラスです。ログイン画面から呼び出されます。

authentication.service.ts

export class AuthenticationService {
  constructor(public afAuth: AngularFireAuth) {}

  /**
   * Google認証を呼び出す。
   * 認証成功時にリダイレクトする。
   *
   * @returns {Promise<void>}
   * @memberof AuthenticationService
   */
  public signInWithGoogle(): Promise<void> {
    return this.afAuth.signInWithRedirect(
      new firebase.auth.GoogleAuthProvider()
    );
  }

  /**
   * リダイレクト後の処理。
   *
   * @returns {Promise<firebase.auth.UserCredential>}
   * @memberof AuthenticationService
   */
  public getRedirectResult(): Promise<firebase.auth.UserCredential> {
    return this.afAuth.getRedirectResult();
  }
}

下記のコードはログイン画面のコンポーネントクラスです。

login.page.ts

export class LoginPage implements OnInit {
  constructor(
    private authenticationService: AuthenticationService,
    private router: Router
  ) {}

  ngOnInit() {
    this.getRedirectResult();
  }

  /**
   * Googleで認証する。
   *
   * @memberof LoginPage
   */
  public async signInWithGoogle() {
    await this.authenticationService.signInWithGoogle();
  }

  /**
   * リダイレクト後に呼び出される処理。
   *
   * @private
   * @memberof LoginPage
   */
  private async getRedirectResult() {
    const result: firebase.auth.UserCredential = await this.authenticationService.getRedirectResult();
    try {
      if (result.user != null) {
        this.router.navigate(['/weight/tabs/tab1']);
      }
    } catch (error) {
      console.log(error);
    }
  }
}

上記のコードで行っているのは、下記の内容です。

  1. ユーザーがsignInWithGoogle()でログインします。
  2. Google でログインを行うため、signInWithRedirect()メソッドによってリダイレクトがトリガーされます。
  3. Googleログインをすると、ユーザーはログイン画面のコンポーネントに戻されます。
  4. ユーザーのログインは、ログイン画面のngOnInit()内のgetRedirectResult()で返される Promise によって解決されます。
  5. navigate()メソッドで、ルーターがユーザーを/weight/tabs/tab1に移動させます。

参考サイト

ログインにおけるブランドの取り扱いガイドライン  |  Google Identity Platform  |  Google Developers