firebase登录验证_Firebase身份验证并做出React以保护您的路由

firebase登录验证

One of the most common requirements in web apps is to prevent unauthorized access to certain routes. For example, you may need to allow only signed-in users to visit the /profile route in your app. This task may seem daunting to beginners.

Web应用程序中最常见的要求之一是防止未经授权的用户访问某些路由。 例如,您可能需要仅允许登录用户访问您应用中的/ profile路由。 对于初学者来说,这项任务似乎艰巨。

Image for post
Photo by Ferenc Almasi on Unsplash
Ferenc AlmasiUnsplash拍摄的照片

This tutorial requires familiarity with react context and react-hooks. If you know how to setup firebase and firebase auth in a react app, its good, but if you don’t, it’s not a problem. You can follow along and do that later. But, knowledge of the two things mentioned above are kind of must.

本教程要求熟悉react上下文react-hooks 。 如果您知道如何在react应用程序中设置firebase和firebase auth,那很好,但是,如果您不知道,这不是问题。 您可以按照后续操作。 但是,必须了解上述两件事。

We will create a Firebase auth provider which will allow us to consume the authentication data anywhere in the app. We create AuthContext with the following default values

我们将创建一个Firebase身份验证提供程序,使我们可以在应用程序中的任何位置使用身份验证数据。 我们使用以下默认值创建AuthContext

createContext( {userDataPresent:false, user:null} )

The idea is to update userDataPresent and user values as the authentication state changes in our app. This is done by updating the state using the useState hook. The onAuthStateChanged method provided by Firebase is used to listen for the changes in authentication state and if a change occurs, update the state accordingly (example below). Changing the state changes the context value that’s being passed down to the consumers and the consumers are able to react accordingly. Since our FirebaseAuthContext component will sit at the highest level in the component tree, any changes made to the state(and in turn, the context value) will force re-render of the rest of the components. Which means, signing out from protected routes will force a redirect. All of this can be seen happening in the example below.

这个想法是随着应用程序中身份验证状态的更改来更新userDataPresent用户值。 这是通过使用useState挂钩更新状态来完成的。 Firebase提供的onAuthStateChanged方法用于侦听身份验证状态的更改,如果发生更改,请相应地更新状态(以下示例)。 更改状态会更改传递给使用者的上下文值,并且使用者能够做出相应的React。 由于我们的FirebaseAuthContext组件将位于组件树中的最高级别,因此对状态所做的任何更改(以及上下文值)都将强制重新渲染其余组件。 这意味着从受保护的路由注销将强制重定向。 在下面的示例中可以看到所有这些情况。

One thing to note here is that, we keep the value returned by the onAuthStateChanged listener in the state after the initial mount ( the event listener returns a function to unsubscribe to the authentication events). This allows us to unsubscribe when the component is unmounted. This can be seen happening inside the useEffect hook.

这里要注意的一件事是,我们将onAuthStateChanged侦听器返回的值保持在初始安装后的状态(事件侦听器返回一个取消订阅身份验证事件的函数)。 这使我们可以在卸载组件时取消订阅。 可以看到这发生在useEffect挂钩中。

import React, {createContext,useState, useEffect} from 'react';
import {auth} from './firebase';
export const AuthContext= createContext({userPresent:false,user:null})
export default function FirebaseAuthContext(props){
    
   
    let [state,changeState] = useState({
        userDataPresent:false,
        
        user:null,
        listener:null
    })


    useEffect(()=>{
        
        if(state.listener==null){
        
       
        changeState({...state,listener:auth.onAuthStateChanged((user)=>{
            
           if(user)
            changeState(oldState=>({...oldState,userDataPresent:true,user:user}));
            else
            changeState(oldState=>({...oldState,userDataPresent:true,user:null}));
        })});
        
    }
    return ()=>{
      if(state.listener)
        state.listener()
    }
    
    },[])
  
  
  
    return (
        <AuthContext.Provider value={state}>
            {props.children}
        </AuthContext.Provider>
    )
}

The function changeState is called whenever the listener fires with new auth data.

每当侦听器使用新的身份验证数据激发时,就会调用changeState函数

The user variable from the context contains the actual user data. It contains null if the user is not signed in. Check this out for more info on the getting signed-in user data from Firebase.

上下文中的用户变量包含实际用户数据。 如果用户未登录,则它包含null。签出内容以获得有关从Firebase获取登录用户数据的更多信息。

The ProtectedRoute component is the consumer of the context we created earlier. It is basically a wrapper around the Route component provided by react-router.

ProtectedRoute组件是我们先前创建的上下文的使用者。 它基本上是对react-router提供的Route组件的包装。

The idea behind, is to return a Redirect if the user is not signed in , else, return a normal Route with an exact path. The userDataPresent is useful to show some kind of spinner (waiting for the auth state to be determined). The code for spinner can be put inside the return statement inside the else block. Now, ProtectedRoute can be used in place of the normal Route to create a protected route which reacts to the changes in the authentication state of the app.

背后的想法是,如果用户未登录,则返回一个Redirect ,否则,返回一个具有精确路径的普通RouteuserDataPresent可用于显示某种微调器(等待确定auth状态)。 旋转器的代码可以放在else块的return语句中。 现在,可以使用ProtectedRoute代替普通路由来创建受保护的路由,该路由对应用程序身份验证状态的更改做出React。

我如何使用 (How I use it)

<Switch>
<Route exact path="/Login">
<div id="firebaseui-auth-container">Login</div>
</Route> <ProtectedRoute redirectTo="/Login" path="/Home">
<div>Home</div>
</ProtectedRoute>
<Route exact path="/">
<div>Root</div>
</Route></Switch>

It’s important not to forget about the FirebaseAuthContext. The component should wrap within itself the routes for it to work since it is the Provider.

重要的是不要忘记FirebaseAuthContext。 由于组件是提供者 ,因此组件应在其内部包装路由以使其工作。

I’m sure there are other (better) ways to handle what I wanted to. But this is simple and easy for beginners to grasp.

我确信还有其他(更好)的方式来处理我想要的事情。 但这对于初学者来说很容易理解。

Let me know if it helps you :)

让我知道它是否对您有帮助:)

翻译自: https://medium.com/swlh/firebase-authentication-and-react-protecting-your-routes-18d6da04b4c3

firebase登录验证

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值