使用Angular和Firebase Authentication轻松创建社交登录
你好,我是Soup。
我将使用Angular和Firebase来轻松实现社交登录。我将按照Angular与Firebase实现简易身份验证的方法进行操作。
步骤
-
- Firebaseのプロジェクト作成
-
- 環境設定
- コードを書く
创建Firebase项目
在Firebase控制台上创建一个项目。
选择使用的“Sign-in providers”并进行启用。
在代码示例中,我们使用了Google和Twitter。
启用身份验证→启用登录方式并使用登录提供商。

不同的提供商可能需要进行密钥/密令等设置。
例如,在创建Twitter应用程序后,需要获取API密钥和API密令,并进行设置。
→Twitter应用程序管理
环境配置
安装 angular-cli
$ npm install -g angular-cli
使用 anglar-cli 进行脚手架生成
$ ng new firebase-auth-sample
$ cd firebase-auth-sample
启动开发服务器
$ ng serve
请在浏览器中访问 localhost:4200
我将使用AngularFire2和Firebase的模块。
$ npm install angularfire2 firebase --save
$ npm install @types/firebase --save-dev
在tsconfig.json中添加types。
(Add types in tsconfig.json.)

写代码
点击Firebase控制台中的WEB SETUP,会弹出一个设置的窗口,将其复制并粘贴到app.module.ts中。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {
AngularFireModule,
AuthMethods,
AuthProviders
} from "angularfire2";
import { AppComponent } from './app.component';
// ポップアップの設定をここに貼り付ける
const firebaseConfig = {
apiKey: "<your-apiKey>",
authDomain: "<your-auth-Domain>",
databaseURL: "<your-database-URL>",
storageBucket: "<your-storage-Bucket>"
};
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AngularFireModule.initializeApp(firebaseConfig,{
provider: AuthProviders.Twitter,
method: AuthMethods.Popup
// method: AuthMethods.Redirect // Redirectが良いならこっち
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
AngularFire的auth是可观察的,因此可以订阅。
import { Component } from '@angular/core';
import { AngularFire, AuthProviders } from 'angularfire2';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
user = {};
constructor(public af: AngularFire) {
this.af.auth.subscribe(user => {
if(user) {
this.user = user;
console.log(this.user);
}
else {
this.user = {};
}
});
}
login(from: string) {
this.af.auth.login({
provider: this._getProvider(from)
});
}
logout() {
this.af.auth.logout();
}
private _getProvider(from: string) {
switch(from){
case 'twitter': return AuthProviders.Twitter;
case 'google': return AuthProviders.Google;
}
}
}
<button (click)="login('google')">
Google Login
</button>
<button (click)="login('twitter')">
Twitter Login
</button>
<button (click)="logout()">
Logout
</button>

您可以在 Firebase 控制台中查看用户信息。
您还可以轻松地在这里启用或禁用用户,以及停用用户。

代码放在这里。
请参考
-
- Angular Authentication made easy with Firebase
- Angularfire2