gpt4 book ai didi

node.js - 如何使用 MongoDB + NodeJS Express 向 ReactJS React Router 和 Redux 添加登录身份验证和 session ?

转载 作者:IT老高 更新时间:2023-10-28 13:30:25 26 4
gpt4 key购买 nike

我有一个 MongoDB + NodeJS Express 服务器,正在运行 Webpack,并且能够使用数据库凭据注册用户。我现在想在用户登录时添加身份验证和 session 。我正在研究 Passport.js 但似乎无法掌握如何将所有内容放在一起。

最好的方法是什么?任何示例和指导将不胜感激。

到目前为止,这些是我的设置。

对于服务器:

var express = require('express');
var path = require('path');
var config = require('../webpack.config.js');
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var bodyParser = require('body-parser');
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectID;

var app = express();
var db;

var compiler = webpack(config);

app.use(webpackDevMiddleware(compiler, {noInfo: true, publicPath: config.output.publicPath}));

app.use(webpackHotMiddleware(compiler));

app.use(express.static('dist'));

app.use(bodyParser.json());

app.post('/api/users/', function(req, res) {
console.log('Req body', req.body);
var newUser = req.body;
db.collection('users').insertOne(newUser, function(err, result) {
if(err) console.log(err);
var newId = result.insertedId;

db.collection('users').find({_id: newId}).next(function(err, doc) {
if(err) console.log(err);
res.json(doc);
})
})
})

app.get('/', function (req, res) {
res.sendFile(path.resolve('client/index.html'));
});

MongoClient.connect('mongodb://localhost/testdb', function(err, dbConnection) {
if(err) console.log(err);

db = dbConnection;
var server = app.listen(3000, function() {
var port = server.address().port;
console.log("Started server at port", port);
});
});

至于路由器(登录页面在Login,注册页面在Register呈现):

//react-router
render(
<div>
<Provider store={store}>
<Router history={hashHistory}>
<Route
component ={MainPage}
path='/'
>
<IndexRoute component={Login}/>
<Route
component={Register} path="Register"
/>
</Route>
</Router>
</Provider>
</div>,
document.getElementById('app')
)

redux 中的 API POST 请求:

//How registered user's credentials are stored via action in redux
registerUser(username, email, name, password) {
console.log('Started registering request')
var user = {
username: username,
email: email,
name: name,
password: password,
}

var request = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
}

console.log('Adding user: ', user)

fetch(`http://localhost:3000/api/users`, request)
.then(res => res.json())
.then(user => {
console.log(user);
return user;
})
.catch(err => {
console.log('Error is', err)
})

console.log('Ending registering request')
},

最佳答案

我推荐你使用这个 JWT 库,它与 expressJs 完美结合 https://www.npmjs.com/package/jsonwebtoken ,在您的用户登录后,您给主题一个 JWT token ,如下所示:

const token = jwt.sign(
{ userId: user.userId, username: user.username },
yourFileWItchContainTheJwtString.jwtSecret,
{ expiresIn: "1h" }//keep connected for 1 hour
);

如果您想验证用户的 JWT 以保持他们的连接或给予他们一些授权,您可以使用以下方法进行验证:

jwtPayload = <any>jwt.verify(token, yourFileWItchContainTheJwtString.jwtSecret);
//save it in locals
res.locals.jwtPayload = jwtPayload;

//从请求头部获取jwt token (对 token 做一些操作)

const token = <string>req.headers["auth"];

您可以查看文档 https://www.npmjs.com/package/jsonwebtoken

关于node.js - 如何使用 MongoDB + NodeJS Express 向 ReactJS React Router 和 Redux 添加登录身份验证和 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39259221/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com