Angular Firebase による Google アカウント認証(ログイン・ログアウト)の実装方法
Angular アプリケーションで、Firebase にログイン・ログアウトの実装方法を紹介します。予め、Firebase が使えるようになっていることが前提になります。
準備として、Firebase の「Authentication」画面で、Google を有効にしておきます。

アプリケーション側では、まずはパッケージとして firebase と angular/fire をインストールします。
npm i firebase @angular/fireAngular アプリケーションの environment.ts に、Firebase の設定情報を転記します。設定情報は、Firebase の「Project Overview」から取得してきます。
export const environment = { production: false, firebase: { apiKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', authDomain: 'xxxx-xxxx-xxxxx.xxxxxxxxxxx.xxx', databaseURL: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', projectId: 'xxxx-xxxx-xxxxx', storageBucket: 'xxxx-xxxx-xxxxx.xxxxxxx.xxx', messagingSenderId: 'xxxxxxxxxxxx' }};AppModule で AngularFireModule と AngularFireAuthModule をインポートします。environment.ts で転記した Firebase の設定情報を、AngularFireModule.initializeApp の引数として渡します。
import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { environment } from '../environments/environment';import { AngularFireModule } from '@angular/fire';import { AngularFireAuthModule } from '@angular/fire/auth';import { AppComponent } from './app.component';@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AngularFireModule.initializeApp(environment.firebase), // 追加 AngularFireAuthModule, // 追加 ], providers: [], bootstrap: [AppComponent]})export class AppModule { }ngOnInit で、AngularFireAuth の authState を変数で参照します。ログイン時に呼び出す login メソッドでは、AngularFireAuth の auth.signInWithRedirect メソッドを利用します。ログアウト時に呼び出す logout メソッドでは、auth.signOut メソッドを利用します。
import { Component, OnInit } from '@angular/core';import * as firebase from 'firebase';import { AngularFireAuth } from '@angular/fire/auth';import { Observable } from 'rxjs';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent implements OnInit { title = 'auth-test'; user$: Observable<firebase.User>;
constructor(private afAuth: AngularFireAuth) { }
ngOnInit() { this.user$ = this.afAuth.authState; }
login() { const provider = new firebase.auth.GoogleAuthProvider(); this.afAuth.auth.signInWithRedirect(provider); }
logout() { this.afAuth.auth.signOut(); }}ユーザーがログインしていれば、ユーザー名を表示し、ログインしていなければ、ログイン用のボタンを表示します。ログインボタンを押すと、Google アカウントでのログイン画面が表示されるので、ログインします。すると、ログインしたユーザー名が画面に表示されます。
<ng-template #loginButton> <button (click)="login()">Login with Google</button></ng-template><div *ngIf="user$ | async as user; else loginButton"> ユーザー : {{user.displayName}} <button (click)="logout()">Logout</button></div>以上、Google アカウントによるログイン認証の方法でした。
💬 コメント