firebase使用_使用Firebase轻松进行角度认证

firebase使用

by Wassim Chegham

由Wassim Chegham

使用Firebase轻松进行角度认证 (Angular Authentication made easy with Firebase)

UPDATE: The code in this article has been updated to Angular Final. We also assume that you’re using the latest Angular CLI.
更新:本文中的代码已更新为Angular Final。 我们还假设您使用的是最新的Angular CLI。

Any serious Web application requires some sort of authentication feature. In this blog post, we’ll set up this feature for an Angular application using Firebase, thanks to the official AngularFire2 library.

任何严肃的Web应用程序都需要某种身份验证功能。 在此博客文章中,由于官方的AngularFire2库,我们将为使用Firebase的Angular应用程序设置此功能。

创建一个新的Firebase项目 (Create a new Firebase project)

Before using Firebase with our application, we need to create a new project in our Firebase developer console:

在将Firebase与我们的应用程序一起使用之前,我们需要在Firebase开发人员控制台中创建一个新项目:

To use the Firebase Authentication feature, we need to enable the sign-in providers we want to use in our project. In our case, we’re going to use Google, Facebook, Twitter and Github to log in our users.

要使用Firebase身份验证功能,我们需要启用要在项目中使用的登录提供程序 。 在我们的案例中,我们将使用Google,Facebook,Twitter和Github登录我们的用户。

You can find the Authentication page in: Your App → Auth → SIGN-IN METHOD:

您可以在以下位置找到“身份验证”页面:您的应用程序→身份验证→登录方法:

Some providers, such as Facebook, Twitter and Github, require you to provide an App/Client/API ID and App/Client/API secret keys, and use the given OAuth URI as the redirect URI:

某些提供程序,例如Facebook,Twitter和Github,要求您提供App / Client / API IDApp / Client / API秘密密钥,并使用给定的OAuth URI作为重定向URI:

In order to obtain this information, you will need to create one application for each provider using your developer account of each service (Github, Facebook and Twitter).

为了获得此信息,您将需要使用每个服务(Github,Facebook和Twitter)的开发者帐户为每个提供商创建一个应用程序。

配置服务 (Configure your services)

For Github, go to your developer settings, and register a new application.

对于Github,转到您的开发人员设置 ,然后注册一个新的应用程序。

Use your application Client ID and Client Secret in your Firebase configuration page.

在Firebase配置页面中使用您的应用程序客户端ID客户端密钥

You also need to fill in the Authorization callback URL using the OAuth URI from Firebase.

您还需要使用Firebase中的OAuth URI填写授权回调URL

For Twitter, go to your Application Management settings, and create a new application.

对于Twitter,请转到“ 应用程序管理”设置 ,然后创建一个新应用程序。

Use your application API key and API Secret in your Firebase configuration page.

在Firebase配置页面中使用您的应用程序API密钥API Secret

You also need to fill in the Callback URL (in the Settings tab) using the OAuth URI from Firebase.

您还需要使用Firebase中的OAuth URI填写“ 回调URL” (在“设置”标签中)。

Finally, for Facebook, go to your developer apps home page, and click on the “Add New App” green button at the upper-right corner.

最后,对于Facebook,请转到您的开发人员应用程序主页,然后单击右上角的“添加新应用程序”绿色按钮。

Use your App ID and App Secret in your Firebase configuration page.

在Firebase配置页面中使用您的App IDApp Secret

You also need to add a new Web platform. Click on +Add platform at the bottom of the page—and fill in the Site URL with the redirect URI from Firebase (i.e. OAuth URI).

您还需要添加一个新的Web平台。 单击页面底部的+ Add platform —并使用Firebase中的重定向URI(即OAuth URI )填写网站URL。

Now you are ready to use Google, Twitter, Github and Facebook as your authentication providers for your web application.

现在,您可以使用Google,Twitter,Github和Facebook作为Web应用程序的身份验证提供程序。

在您的应用程序中使用AngularFire (Use AngularFire in your application)

For the next step, I’m going to use an Angular application I scaffolded thanks to the official Angular CLI.

下一步,由于官方的Angular CLI ,我将使用一个脚手架上的Angular应用程序。

In this application, I’m going to use the Authentication providers we just set up in the previous step.

在此应用程序中,我将使用上一步中刚刚设置的身份验证提供程序。

Here’s what the application looks like:

这是应用程序的外观:

Clicking on a button will call a specific provider, authenticate the user, and get their information:

单击一个按钮将呼叫特定的提供者,对用户进行身份验证并获取其信息:

安装和设置angularfire2 (Install and setup angularfire2)

First things first, we need to install the firebase and angularfire2 libraries:

第一件事首先,我们需要安装的火力angularfire2库:

$ npm install angularfire2 firebase --save

Then we need to install Firebase types:

然后,我们需要安装Firebase类型:

$ npm install @types/firebase

And add those types to your src/tsconfig.json file:

并将这些类型添加到您的src / tsconfig.json文件中:

{  "compilerOptions": {    "declaration": false,    "emitDecoratorMetadata": true,    "experimentalDecorators": true,    "lib": ["es6", "dom"],    "mapRoot": "./",    "module": "es6",    "moduleResolution": "node",    "outDir": "../dist/out-tsc",    "sourceMap": true,    "target": "es5",    "typeRoots": [      "../node_modules/@types"    ],    "types": [      "jasmine",      "firebase",      "node"    ]  }}

A more detailed setup process is described in the official docs.

官方文档中描述了更详细的设置过程。

为您的应用程序配置AngularFire (Configure AngularFire for your Application)

In order to use Firebase with Angular, we need to provide some configuration for the AngularFire services.

为了将Firebase与Angular结合使用,我们需要为AngularFire服务提供一些配置。

Let’s start with the default Firebase configuration which looks like this:

让我们从如下所示的默认Firebase配置开始:

defaultFirebase({  apiKey: "AIzaSyCk3weREVFpOIN6pL_QVVNFRl3C3keMIRU",  authDomain: "angular2-auth.firebaseapp.com",  databaseURL: "https://angular2-auth.firebaseio.com",  storageBucket: "angular2-auth.appspot.com"})

Note: Don’t worry about this exposed apiKey. This key is only used to identify the different services of your project: a kind of project identifier.

注意:不用担心这个暴露的apiKey 该密钥仅用于标识项目的不同服务:一种项目标识符。

You can get your Firebase apiKey, projectId, databaseName, and bucket ID from your application dashboard.

您可以从应用程序仪表板获取Firebase apiKeyprojectId,databaseName存储桶ID

Click on the WEB SETUP button in the top-right corner:

单击右上角的WEB SETUP按钮:

Next, for our use case, we want to provide a default authentication method:

接下来,对于我们的用例,我们要提供一种默认的身份验证方法:

firebaseAuthConfig({  method: AuthMethods.Popup})

Here, we choose to use a Popup to allow the user to log in. We could also use a Redirect method like this:

在这里,我们选择使用弹出窗口来允许用户登录。我们还可以使用如下的Redirect方法:

firebaseAuthConfig({  method: AuthMethods.Redirect})

Let’s now create a CoreModule in src/app/core.module.ts where we will put our configuration. It is best practice to group core dependencies in a separate NgModule named CoreModule. Here is an example of such module:

现在让我们在src / app / core.module.ts中创建一个CoreModule,在其中放置我们的配置。 最佳做法是将核心依赖项分组在一个单独的名为CoreModule的 NgModule中。 这是此类模块的示例:

import { BrowserModule } from '@angular/platform-browser';import { HttpModule } from '@angular/http';import { NgModule } from '@angular/core';import { FormsModule } from '@angular/forms';import {   AngularFireModule,   AuthMethods,   AuthProviders } from "angularfire2";
const firebaseConfig = {  apiKey: "AIzaSyCk3weREVFpOIN6pL_QVVNFRl3C3keMIRU",  authDomain: "angular2-auth.firebaseapp.com",  databaseURL: "https://angular2-auth.firebaseio.com",  storageBucket: "angular2-auth.appspot.com"};
@NgModule({  imports: [    BrowserModule,    FormsModule,    HttpModule,    AngularFireModule.initializeApp(firebaseConfig,{      provider: AuthProviders.Google,      method: AuthMethods.Popup    })  ],  exports: [    BrowserModule,  ]})export class CoreModule {}
在组件中使用它 (Using it in your components)

Now we’re finally ready to implement the authentication feature for our Angular application.

现在,我们终于可以为Angular应用程序实现身份验证功能了。

We need to inject the AngularFire service in the component’s constructor:

我们需要在组件的构造函数中注入AngularFire服务:

import { Component } from '@angular/core';import { AngularFire, AuthProviders } from 'angularfire2';
@Component({  moduleId: module.id,  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) {        // user logged in        this.user = user;      }      else {        // user not logged in        this.user = {};      }    });  }}

In a real world application, you would create a separate service that handles authentication. Think SRP and DRY. But for this tutorial, we will keep it simple.

在实际的应用程序中,您将创建一个单独的服务来处理身份验证。 考虑一下SRPDRY 。 但是对于本教程,我们将使其保持简单。

The AngularFire service gives us the auth property which implements the Observable API. So that means we need to subscribe to this auth property in order to get the authentication state. A NULL value means the user is not logged in.

AngularFire服务为我们提供了实现Observable API的auth属性。 因此,这意味着我们需要预订此auth属性才能获取身份验证状态。 NULL值表示用户未登录。

Let’s add a couple of buttons in the component’s view:

让我们在组件的视图中添加几个按钮:

<button md-raised-button (click)="login()">  <img width="30" src="google-logo.png" />Use My Google Account</button><button md-raised-button (click)="logout()">  Logout</button>

We will use those buttons to log in and log out, using the Google provider as an example.

我们将使用这些按钮登录和注销,以Google提供程序为例。

In app.component.ts, we need to implement the login() and logout() methods:

app.component.ts中 ,我们需要实现login() logout()方法:

login() {  this.af.auth.login({    provider: AuthProviders.Google  });} logout() {  this.af.auth.logout();}

To log a user in, we call the this.af.auth.login() method using the Google provider, and this.af.auth.logout() to log a user out.

要登录用户,我们使用Google提供程序调用this.af.auth.login()方法,并使用this.af.auth.logout()退出用户。

The AngulareFire login() usually needs an authentication method. In our case, it will use the default method (i.e. AuthMethods.Popup) we set up in the bootstrap phase.

AngulareFire login()通常需要一种身份验证方法。 在我们的例子中,它将使用我们在引导阶段设置的默认方法(即AuthMethods.Popup)

If you need to override the authentication method when calling the login() method, just provide a new auth configuration:

如果在调用login()方法时需要覆盖身份验证方法,则只需提供一个新的auth配置:

login() {  this.af.auth.login({    provider: AuthProviders.Google,    method: AuthMethods.Redirect  });}

Once everything is setup and working correctly, we can inspect the user object containing all the user’s session tokens sent by Google (the authentication provider):

一切设置完成并正常工作后,我们可以检查包含Google(身份验证提供程序)发送的所有用户会话令牌的用户对象:

You can get the user’s information such the displayName and the photoURL form the auth.provideData entry.

您可以从auth.provideData条目中获取用户信息,例如displayNamephotoURL

That’s it! Your users can now log in using their Google accounts.

而已! 您的用户现在可以使用其Google帐户登录。

You can add Github and Facebook in much the same way.

您可以以几乎相同的方式添加Github和Facebook。

See the complete working application hosted on Firebase or read the complete source code on Github.

请参阅Firebase上托管的完整的可运行应用程序在Github上阅读完整的源代码。

NOTE: I’m in the process of migration this repo to Angular final (see branch). This process is pending because of this issue in AngularFire2.

注意:我正在将此仓库迁移到Angular final中( 请参阅分支 )。 由于AngularFire2中的此问题 ,该过程正在等待中。

manekinekko/angular-firebase-authenticationangular-firebase-authentication - An angular demoing Firebase Authentication providersgithub.com

manekinekko / angular-firebase-authentication angular-firebase-authentication-角度演示Firebase身份验证提供程序 github.com

提示与参考 (Tips & References)

Follow @manekinekko to learn more about the web platform.

关注@manekinekko以了解有关Web平台的更多信息。

翻译自: https://www.freecodecamp.org/news/angular-2-authentication-made-easy-with-firebase-246c282d9ef8/

firebase使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值