我学习了jwt
和passport
,我试图在登录后使用更正的凭据进行验证,但是它总是返回401 Unauthorized
,我不知道为什么。
我的代码node.js确实生成了jwt
:
const express = require('express');
const bodyParser = require('body-parser');
const _ = require("lodash");
const app = express();
const jwt = require('jsonwebtoken');
const passport = require('passport');
const passportJWT = require('passport-jwt');
const ExtractJwt = passportJWT.ExtractJwt;
const JwtStrategy = passportJWT.Strategy;
app.use(passport.initialize());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
var jwtOptions = {}
jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');
jwtOptions.secretOrKey = 'tasmanianDevil';
var strategy = new JwtStrategy(jwtOptions, function(jwt_payload, next) {
console.log('payload received', jwt_payload);
var user = users[_.findIndex(users, {
id: jwt_payload.id
})];
if (user) {
next(null, user);
} else {
next(null, false);
}
});
passport.use(strategy);
var users = [{
id: 1,
name: 'jonathanmh',
password: '%2yx4'
},
{
id: 2,
name: 'test',
password: 'test'
}
];
app.post("/login", function(req, res) {
if (req.body.name && req.body.password) {
var name = req.body.name;
var password = req.body.password;
}
var user = users[_.findIndex(users, {
name: name
})];
if (!user) {
res.status(401).json({
message: "no such user found"
});
}
if (password === user.password) {
var payload = {
id: req.body.id
};
var token = jwt.sign(payload, jwtOptions.secretOrKey);
res.send({
message: "ok",
token: token
});
} else {
res.status(401).json({
message: "passwords did not match"
});
}
});
我的路线受到保护:
app.get('/pageOwnerAgency', passport.authenticate('jwt', { session: false }), (req, res) => {
res.send({message: 'foi'})
});
我了解的是,以上路由验证是否存在jwt
。但这不起作用...
执行ajax的组件:
handleLogin = () => {
axios.post('/login', { name: this.state.name, password: this.state.password })
.then(res => {
localStorage.setItem('jwt', res.data.token)
window.location.reload();
})
.catch(error => console.log(error.response.data.message))
}
和我的页面ownerAgency来获取消息:
componentDidMount() {
axios.get('/pageOwnerAgency')
.then(res=>console.log(res.data.message))
.then(error=>console.log(error))
}
有人帮我吗?