vue firebase_这是使用Vue.js和Firebase对用户进行身份验证的方法

vue firebase

by Gareth Redfern

加雷斯·雷德芬(Gareth Redfern)

这是使用Vue.js和Firebase对用户进行身份验证的方法 (Here is how to authenticate users using Vue.js and Firebase)

In this tutorial we will work through building a simple Vue.js app. It will use Firebase for authentication and allow users to sign-up. Once signed-up users access protected areas of a web application via a sign-in page.

在本教程中,我们将构建一个简单的Vue.js应用程序。 它将使用Firebase进行身份验证,并允许用户注册。 注册后,用户可以通过登录页面访问Web应用程序的受保护区域。

To keep things as simple and short as possible an assumption is made that you are familiar with Vue.js. You can get up and running with a project using the CLI and webpack. We will work through two main topics to create our app:

为了使事情尽可能简单和简短,我们假设您熟悉Vue.js。 您可以使用CLIwebpack启动并运行一个项目。 我们将通过两个主要主题来创建我们的应用程序:

  1. Using the vue-router 2 to load and protect pages of the web app.

    使用vue-router 2加载和保护Web应用程序的页面。

  2. Set up a Firebase back end that uses Firebase authentication to manage a user sign-up and sign-in.

    设置使用Firebase身份验证的Firebase后端,以管理用户注册和登录。

The tutorial files are free to download on github. Where possible comments have been added to explain what the code is doing. To get the site up and running on your local machine follow the instructions in the README file. The main directory we will be writing our code in is the src directory. If you have built Vue apps in the past this should be familiar to you.

教程文件可在github上免费下载。 在可能的地方添加了注释以解释代码的作用。 要在本地计算机上启动并运行该站点,请按照README文件中的说明进行操作。 我们将在其中编写代码的主目录是src目录。 如果您过去曾经构建过Vue应用程序,那么您应该对此很熟悉。

应用架构 (App Architecture)

The app we are building will have a simple home page where a user navigates to access the site. They will need to sign-up for an account with a sign-up form. Once registered, a sign-in page will enable the user to access a dashboard (the secure area of the site).

我们正在构建的应用程序将具有一个简单的主页,用户可以在其中导航以访问该网站。 他们将需要使用注册表格注册一个帐户。 注册后,登录页面将使用户能够访问仪表板(站点的安全区域)。

处理路线和保护页面 (Handling Routes and Securing Pages)

The first concept to understand is how to send page requests and secure the pages behind a sign-in. To do this we will install vue-router 2, a first party library for handling routes. To get a good understanding of simple routes we will ignore securing any pages at first. Lets set up the site structure:

要理解的第一个概念是如何发送页面请求并在登录后保护页面的安全。 为此,我们将安装vue-router 2 ,这是用于处理路由的第一方库。 为了更好地理解简单路由,我们将首先忽略保护任何页面的安全。 让我们设置站点结构:

  • Home

  • Sign-up

    注册
  • Sign-in

    登入
  • Dashboard (We will secure this page eventually)

    信息中心(我们将最终保护此页面)
  • Error/404 (catch-all page)

    错误/ 404(全部页面)

There are two main files to review to gain a basic understanding of what the vue-router does. In the main.js file we import the VueRouter and tell Vue that you want to use it. Next we create a VueRouter instance and pass in the routes that the app will use via a separate routes.js file.

需要审查两个主要文件,以基本了解vue-router的功能。 在main.js文件中,我们导入VueRouter并告诉Vue您要使用它 。 接下来,我们创建一个VueRouter实例,并通过单独的route.js文件传入应用程序将使用的路由。

Here we also set the mode for the router to us, out of the box the vue-router will load each page with a hash in the URL. In modern browsers we can use the HTML5 History API and remove the need to have the hash in the URL.

在这里,我们还为我们设置了路由器的模式,开箱即用的vue-router会在URL中为每个页面加载一个哈希。 在现代浏览器中,我们可以使用HTML5历史记录API,而无需在URL中使用哈希。

There would also be some server config to get this to work, for more info read the official docs.

也将有一些服务器配置使它起作用,有关更多信息,请阅读官方文档

Vue.use(VueRouter);
const router = new VueRouter({ routes: routes,  mode: 'history'} );

The routes.js file imports all the components that you will display throughout the site. It exports an array of all your routes as objects. Each object has the following key value pairs:

route.js文件导入您将在整个站点中显示的所有组件。 它将所有路由数组导出为对象。 每个对象具有以下键值对:

  • route name (optional)

    路线名称(可选)
  • path (the url the user navigates to)

    路径(用户导航到的URL)
  • component (Vue component to load)

    组件(要加载的Vue组件)

To explain a little further have a look at the following code:

为了进一步解释,请看以下代码:

{
path: '/sign-in', // set the URL the user will visit
name: 'signIn', // use this name as a shortcut in your links
component: SignIn // load the SignIn component
}

For each route we repeat the above code and swap out the properties for all our route options. Next we will add the <router-view></router-view> opening and closing tags to the App.js file. These act as placeholders, telling Vue where to swap out the components when a route path is selected. With this in place you should be able to navigate to each URL and the component for that path will load.

对于每条路线,我们重复上面的代码,并交换所有路线选项的属性。 接下来,我们将<router-view></rou >的开始和结束tags t到App.js文件中。 它们充当占位符,告诉Vue当选择了路径时在哪里交换组件。 使用此功能,您应该能够导航到每个URL,并且将加载该路径的组件。

固定路线 (Securing Routes)

The vue-router provides a way to secure routes using Navigation Guards. There are three levels of guard that you can work with:

vue-router提供了一种使用Navigation Guards保护路线的方法。 您可以使用三种级别的防护:

  • Global guards (what we will use) are set once on the route instance.

    全局防护(我们将使用的防护)在路由实例上设置一次。
  • Per-route guards are set on each route separately.

    每个路径的防护分别设置在每个路径上。
  • In-component guards are set in each component.

    在每个组件中都设置了组件内防护。

You could opt to use any of these methods but for simplicity we will set the guard to run globally on every page load, this probably has the greatest overhead so just bare that in mind. To get our secure routes working we will check two things:

您可以选择使用这些方法中的任何一种,但是为简单起见,我们将防护设置为在每次页面加载时全局运行,这可能具有最大的开销,因此请记住。 为了使我们的安全路线正常运行,我们将检查两件事:

  1. Does the route have a meta property with requiresAuth set to true.

    路由是否具有meta属性,且requiresAuth设置为true。

  2. Is the user logged in and authenticated via the Firebase authentication.

    用户是否已登录并通过Firebase身份验证进行了身份验证。

Lets work through the above points to better understand what is happening. The vue-router has route meta fields where you can add data to retrieve for that particular route. We can use this to set a simple boolean requiresAuth for our protected pages:

让我们通过以上几点来更好地了解正在发生的事情。 Vue路由器具有路由元字段 ,您可以在其中添加数据以检索该特定路由。 我们可以用它来设置一个简单的布尔requiresAuth我们保护的页面:

{   path: '/dashboard',   name: 'dashboard',   component: Dashboard,   meta: {    requiresAuth: true   }},

With the above code in place, we check to see if the route requires authentication before it loads. This check uses the global navigation guard set in the main.js file.

使用上面的代码,我们检查路由是否在加载之前需要身份验证。 此检查使用main.js文件中设置的全局导航保护。

router.beforeEach((to, from, next) => {
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
if(requiresAuth) {   next('/sign-in');} else {  next();}
});

Here we are are calling the beforeEach method on the router instance. It takes 3 arguments explained in detail in the docs but the main one to focus on is the next argument. This is where you tell the router what to do when the requiresAuth condition is set to true.

在这里,我们正在路由器实例上调用beforeEach方法。 它需要3个参数,这些参数在文档中有详细说明,但是要重点关注的是next参数。 当requiresAuth条件设置为true时,您可以在这里告诉路由器该做什么。

In our application we use it to send the user to the sign-in page. To access the route meta data we are setting a constant that takes the to argument (the route we are navigating to). The docs explain how you can access the meta fields that you set:

在我们的应用程序中,我们使用它将用户发送到登录页面。 要访问路线元数据,我们设置了一个常量,该常量采用to参数(导航的路线)。 该文档说明了如何访问您设置的元字段:

All route records matched by a route are exposed on the $route object (and also route objects in navigation guards) as the $route.matched Array. Therefore, we will need to iterate over $route.matched to check for meta fields in route records.

与路线匹配的所有路线记录都以$route.matched数组形式显示在$route对象(以及导航防护中的路线对象)上。 因此,我们将需要遍历$route.matched以检查路由记录中的元字段。

With the meta array available to us we can iterate over it using a ES6 function:

有了可用的元数组,我们可以使用ES6函数对其进行迭代:

const requiresAuth = to.matched.some(record => record.meta.requiresAuth);

We pass the requiresAuth into the conditional. If true send the user to the sign-in page, if false load the page as normal.

我们通过requiresAuth入条件。 如果为true则将用户引导至登录页面;如果为false ,则照常加载页面。

It’s worth taking the time to read through the docs. Get a good understanding of what the beforeEach method is doing. It is a key principal to understanding route guards. Next we will move on to using Firebase to authenticate the user and add a check to the route guard.

值得花时间阅读文档。 很好地了解beforeEach方法的作用。 这是了解路由守卫的关键原则。 接下来,我们将继续使用Firebase对用户进行身份验证并将检查添加到路由防护中。

使用Firebase进行身份验证 (Authentication With Firebase)

Firebase offers a complete backend and authentication system. It can be added to the front end of your web app. For this demo we will be using it’s authentication API to allow users to sign-up and sign-in. Once signed in, authenticated users can view protected content. The first thing you will need to do is sign up for an account at Firebase. I would also suggest watching getting started with Firebase Auth.

Firebase提供了完整的后端和身份验证系统。 可以将其添加到Web应用程序的前端。 在此演示中,我们将使用其身份验证API允许用户注册和登录。 登录后,经过身份验证的用户可以查看受保护的内容。 您需要做的第一件事是在Firebase上注册一个帐户。 我还建议您观看Firebase Auth入门。

Once you have an account set up you will need to create a project in Firebase. Rather than into this, you can read through the docs on Firebase. They provide an excellent set of instructions to get you started. Note that you will need to copy and paste your config settings and swop them in the project’s main.js. Make sure you enable email & password authentication as the sign in method.

设置帐户后,您将需要在Firebase中创建一个项目。 您可以通读Firebase上的文档 ,而不是阅读本文 他们提供了一套很好的说明,可以帮助您入门。 请注意,您将需要复制并粘贴您的配置设置,并将其入项目的main.js中 。 确保启用电子邮件和密码身份验证作为登录方法。

With Firebase set up and your config settings added. Lets look at the final part of the authentication process. Add a second conditional to the the route guard’s beforeEach method we created earlier.

设置Firebase并添加您的配置设置。 让我们看一下身份验证过程的最后一部分。 向我们先前创建的路由卫士的beforeEach方法中添加第二个条件。

router.beforeEach((to, from, next) => {
const currentUser = Firebase.auth().currentUser;
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
if (requiresAuth && !currentUser) {
next('/sign-in');
} else if (requiresAuth && currentUser) {
next();
} else {
next();
}
});

We have added a variable currentUser, it returns the current signed in user from Firebase. If nobody is signed in then it returns null. We can use this as the second check in our conditional statement. If both requiresAuth and currentUser are true the route will display the page.

我们添加了一个变量currentUser ,它从Firebase返回当前登录的用户。 如果没有人登录,则返回null。 我们可以将其用作条件语句中的第二项检查。 如果requireAuth和currentUser均为true,则路由将显示该页面。

If this condition is not met then it returns the user to a sign-in page. If the route is not protected using the requiresAuth meta tag, the page is loaded as normal and no authentication is required.

如果不满足此条件,则它将使用户返回登录页面。 如果未使用requireAuth元标记保护该路由,则该页面将正常加载,并且不需要身份验证。

确保在加载Vue之前初始化Firebase (Make Sure Firebase is Initialised Before Loading Vue)

Our routes have been set up so that if you have already signed-in then you are redirected to the dashboard page. Unfortunately this will not happen. The execution of the navigation guard beforeEach takes place before Firebase initialisation ends. This is a very important gotcha which Anas Mammeri explains in his post.

我们已经设置了路线,因此,如果您已经登录,那么您将被重定向到仪表板页面。 不幸的是,这不会发生。 每次在Firebase初始化结束之前执行导航卫士beforeEach。 这是一个非常重要的陷阱Anas Mammeri其帖子中解释了这一点

使用Vue处理注册和登录 (Using Vue to Handle the Sign-up & Sign-in)

We need users to be able to sign-up and sign-in to our app. Take a look at the two Vue components SignUp.vue and SignIn.vue. They both work in a similar way, binding the email and password fields to the data property.

我们需要用户能够注册和登录我们的应用程序。 看一下两个Vue组件SignUp.vueSignIn.vue。 它们都以类似的方式工作,将电子邮件和密码字段绑定到data属性。

The integration with Firebase happens when the signUp or signIn method is run. These functions are provided by Firebase. We pass in the email and password from the Vue data property. On success navigate to the dashboard using the vue-router replace method. If any errors occur then an alert with the error message is displayed.

运行signUp或signIn方法时,将与Firebase集成。 这些功能由Firebase提供。 我们通过Vue数据属性传递电子邮件和密码。 成功后,使用vue-router replace方法导航至仪表板。 如果发生任何错误,则显示带有错误消息的警报。

signUp: function() {  Firebase.auth()          .createUserWithEmailAndPassword(this.email, this.password)          .then( user => { this.$router.replace('dashboard'); },          error => { alert(error.message); });}
signIn: function() {  Firebase.auth()          .signInWithEmailAndPassword(this.email, this.password)          .then( user => { this.$router.replace("dashboard"); },          error => { alert(error.message); });}

If you load the site up in your browser you should now be able to sign-up and sign-in. All we need to do now is provide the user with a sign out link.

如果您在浏览器中加载网站,则现在应该可以注册和登录。 我们现在要做的就是为用户提供注销链接。

允许用户退出 (Allowing Users to Sign-out)

Take a look at the Header.vue component. We can use a Firebase signOutmethod which fires when a user clicks the Sign-out button. Then redirect them to the sign-in page with the vue-router replace method.

看一下Header.vue组件。 我们可以使用Firebase signOut方法,该方法在用户单击“注销”按钮时触发。 然后使用vue-router replace方法将它们重定向到登录页面。

signOut: function() {  Firebase.auth()    .signOut()    .then(() => {      this.$router.replace('sign-in');    });}

Load the site up in your browser and click on the sign-out button. You should now be redirected back to the sign-in page.

在浏览器中加载该网站,然后单击退出按钮。 现在,您应该被重定向回登录页面。

总结与进一步学习 (Wrapping Up & Further Learning)

Our app now has basic Firebase authentication with some simple vue-router fundamentals added. Next we need to look at how we manage user state. The state helps display content and links depending on whether a user is logged in. After reviewing a few options it would be a good use case to dive into Vuex.

我们的应用现在具有基本的Firebase身份验证,并添加了一些简单的vue-router基础。 接下来,我们需要研究如何管理用户状态。 该状态有助于根据用户是否登录来显示内容和链接。在查看了几个选项之后, 深入研究Vuex是一个很好的用例。

翻译自: https://www.freecodecamp.org/news/authentication-with-vue-js-firebase-5c3a82149f66/

vue firebase

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值