【发布时间】:2020-08-01 11:25:27
【问题描述】:
我已经为此苦苦挣扎了大约 6 天... 一切都运行良好,例如授权,但我遇到的一个问题是进行身份验证。
在我的用户模型(用于创建数据库架构)上,我确实有办法为登录用户或注册用户生成令牌。
userSchema.methods.generateAuthToken = function(){
const token = jwt.sign({ _id: this._id }, config.get('jwtPrivateKey'));
return token;
}
所以当用户发布到 /login 时,服务器会用一个令牌响应:
router.post('/', async (req, res) =>{
// Here i'm validating data and then if everything is right the code under will run.
console.log('logged in as: ' + user.username);
// Here i'm using the function to generateAuthToken().
const token = user.generateAuthToken();
console.log("Token from server: " + token);
// now here is my main problem i would like to use cookies to store it for an hour or so.
// then client can send it back to server for protected route.
res.status(200).send(token);
});
我已经为 auth 创建了一个中间件功能(如果您正在通过受保护的路线检查令牌)
module.exports = function (req, res, next){
// instead of using headers i would like to check for the cookie value if it's the token,
// pass the user in, else Access denied.
// I have no idea how to use cookie parser with middleware functions.
const token = req.header('x-auth-token');
if(!token) return res.status(401).send('Access denied. Sign in or register.');
try{
const decoded = jwt.verify(token, config.get('jwtPrivateKey'));
req.user = decoded;
next();
}
catch(err){
res.status(400).send('Invalid Token!');
}
}
这里我使用的是 auth 中间件功能:
const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
// but it's actually not passing the user in since i haven't done it with cookies.
router.get('/', auth, (req, res) =>{
res.render('index', {});
});
我知道我可以使用 localStorage 来做到这一点,但这是一种糟糕的做法,最好将其存储在 cookie 上,这样就没有人可以破解了。 有什么好的方法可以解决这个问题吗?我有点迷失了,失去了回到 sessionID 的希望(我不想这样做:()。
【问题讨论】:
标签: javascript node.js express authentication jwt