javascript – 使用ReactJS和Firebase进行身份验证
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 使用ReactJS和Firebase进行身份验证,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含5727字,纯文字阅读大概需要9分钟。
内容图文
我是Web开发的新手,并开始学习ReactJS.
到目前为止,构建简单的Web应用程序没有问题.
现在我想使用Firebase进行身份验证.
我知道如何使用Firebase对用户进行身份验证,但我无法了解如何设计前端来限制对某些页面的访问.
以前,我使用PHP,因为我使用了session变量并包含了包含HTML的部分以向用户显示.
但我不知道如何使用Firebase在ReactJS中执行此操作.
初始和失败的方法:
我想到更新this.state.loggedIn并使用它来显示组件.但这不是一个正确的方法,因为我发送了两个要显示的组件,我们可以轻松地使用Chrome中的React开发人员扩展来更改组件的状态.
这是我的主要index.js代码:
import React from 'react';
import ReactDOM from 'react-dom';
import Login from './components/Login/Login';
import Home from './components/Home/Home';
import fire from './components/Fire';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
loggedIn: false,
};
this.authListener = this.authListener.bind(this);
}
componentDidMount() {
this.authListener();
}
authListener() {
fire.auth().onAuthStateChanged(user => {
if (user) {
// User is signed in.
console.log(user);
this.setState({
loggedIn: true
})
} else {
// No user is signed in.
this.setState({
loggedIn: false
});
}
});
}
render() {
return (
<div>
{this.state.loggedIn ? <Home/> : <Login/>}
</div>
);
}
}
ReactDOM.render(
<App/>, document.getElementById('app'));
在Login.js中,我正在调用Firebase身份验证功能.
只是片段:
fire
.auth()
.signInWithEmailAndPassword(this.state.email, this.state.password)
.catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log(error);
// ...
});
身份验证工作正常,我可以在控制台日志中看到它.
那么,我应该如何在ReactJS Firebase中进行身份验证呢?(它是否可以不使用其他任何包如react-routes等?)
或者我应该使用云功能吗?
解决方法:
更新:
您在html文件中链接的所有内容都应始终来自您的公共目录.因此,请将捆绑的.js文件保存在公共目录中.
我为初学者写了一些节省时间的技巧.你可以找到更多关于初学者的提示here.
它实际上很简单.
如果您只想将所需的html文件发送到浏览器,则每次需要完整的不同html时都必须点击服务器.
你说你用过PHP.在PHP中,我们使用会话来了解某人是否已登录.
所以,我们试着在这里实现它.
首先让我们看一下PHP中的会话是如何工作的.取自SO Answer
In the general situation :
- the session id is sent to the user when his session is created.
- it is stored in a cookie (called, by default,
PHPSESSID
)- that cookie is sent by the browser to the server with each request
- the server (PHP) uses that cookie, containing the session_id, to know which file corresponds to that user.
The data in the sessions files is the content of
$_SESSION
,
serialized (ie, represented as a string — with a function such as
07002) ; and is un-serialized when the file is loaded by
PHP, to populate the$_SESSION
array.Sometimes, the session id is not stored in a cookie, but sent in
URLs, too — but that’s quite rare, nowadays.For more informations, you can take a look at the 07003 section of the manual, that gives some useful
informations.For instance, there is a page about 07004, which
explains how the session id is passed from page to page, using a
cookie, or in URLs — and which configuration options affect this.
所以,session只是一个cookie.然后我想我们可以使用cookie来了解用户登录状态.
在Firebase中,Cookie存在问题.您只能将Cookie名称设置为__session. Firebase会忽略其他名称,因此您无法读取服务器上的Cookie.
您需要使用Firebase函数执行一些后端工作,并根据用户登录状态提供html.
因此,在项目目录中设置Firebase功能.在根中,
$firebase init functions
现在,您必须向Firebase说,任何进入您域的请求都必须调用一个函数.
为此,您必须在firebase.json文件中写入重写.我们的功能名称将是主要的.
{
"database": {
"rules": "database.rules.json"
},
"hosting": {
"public": "/dev",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites":[{
"source": "**",
"function": "main"
}]
}
}
现在在任何地方创建一个index.js(首选项目目录的根目录,因为这是主文件).
index.js
import express from 'express';
import * as functions from 'firebase-functions';
import fs from 'fs';
var cookieParser = require('cookie-parser')
const app = express();
app.use(cookieParser());
app.get('**', (req, res) => {
// Check the custom set cookie for user
// If the user is not logged-in, redirect to Login. Otherwise, redirect to Home page
if (req.cookies.__session == 'loggedin') {
var index = fs.readFileSync(__dirname + '/src/Home/index.html', 'utf8');
}
else {
var index = fs.readFileSync(__dirname + '/src/Login/index.html', 'utf8');
}
res.send(index);
});
export let main = functions.https.onRequest(app);
关于以上部分的一些解释:
> express:用于处理请求并发送响应.
> firebase-functions:Google提供使用Firebase功能.
> fs:我们根据文件系统中的用户登录状态读取相应的html并提供服务.
> cookie-parser:我们使用它来轻松访问我们的cookie.
注意:您需要将其转换为ES5.所以用babel命令转换它(我假设你在root中保存了index.js.)
$babel index.js -d functions
我们使用名为__session的cookie来了解用户登录状态.
如果__session设置为loggedin,我们将向用户Home html发送.否则,我们发送Login html.
现在,真正的问题是:“我们需要在哪里设置cookie __session?”
我们在用户浏览器中设置了cookie.
我们使用onAuthStateChanged().
在您的登录页面组件中调用此方法,如:
componentDidMount() {
this.authListener();
}
authListener() {
fire.auth().onAuthStateChanged(user => {
if (user) {
// User is signed in.
if (Cookies.get('__session') === undefined) {
Cookies.set('__session', 'loggedin', { expires: 3652 });
window.location.reload();
}
} else {
// No user is signed in.
Cookies.remove('__session');
}
});
}
注意:Cookies对象是从js-cookie导入的.因此,请安装它.
我们在这里做的是:
>首先在加载页面时最初调用onAuthStateChanged().
>如果用户已登录,我们将进入if块.
>然后我们检查__session cookie.这很重要,因为有时用户可以清除所有cookie.当我们尝试读取服务器中的cookie时,我们会得到未定义的内容,并将登录页面发送给用户.从1开始重复该过程.
>然后我们重新加载页面.当我们重新加载页面时,用户再次点击服务器.然后我们可以检查__session cookie并将Home html发送给用户.
内容总结
以上是互联网集市为您收集整理的javascript – 使用ReactJS和Firebase进行身份验证全部内容,希望文章能够帮你解决javascript – 使用ReactJS和Firebase进行身份验证所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。