我正在尝试通过通过标头通过标头发送的令牌来授权登录用户。
但是生成令牌后,我将其复制到标头中,并使用postman
发送,但是每次令牌都给我Unauthorized
响应,尽管令牌是立即生成的,并且到期时间为半小时。 / p>
通过登录并发布请求创建token
通过header发送后 Unauthorized
错误
我正在向本地主机发送get
请求,并在标头中添加令牌。
router.get(
"/current",
passport.authenticate("jwt", { session: false }),
(req, res) => {
res.json(req.user);
}
);
server.js是包含的主文件
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const users = require("./routes/api/users");
const profile = require("./routes/api/profile");
const posts = require("./routes/api/posts");
const app = express();
// Body parser middleware to send input data to backend.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// configure database
const db = require("./config/keys").mongoURI;
// connect to database
// if connected successfully then returns promise by "then()"
// if error then catch error and do "anyFunction()" eg.output that error.
mongoose
.connect(
db,
{ useNewUrlParser: true } // added this flag to remove deprecation warning
)
.then(() => {
console.log("MongoDB connected");
})
.catch(err => {
console.log("Error occured.\n" + err);
});
// app.get("/", (req, res) => res.send("app.get is working"));
// Passport middleware after connect and before using routes
app.use(passport.initialize());
// Passport Config file call function and pass argument as function() passport
require("./config/passport")(passport);
// Use following routes from apis imported.
app.use("/api/users", users);
app.use("/api/profile", profile);
app.use("/api/posts", posts);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server is running at port no ${port}`));
我的passport.js
文件包含
const JwtStrategy = require("passport-jwt").Strategy;
const ExtractJwt = require("passport-jwt").ExtractJwt;
const mongoose = require("mongoose");
const User = mongoose.model("users");
// in User.js model file it contains mongoose.model('users', UserSchema);
const keys = require("../config/keys");
const opts = {}; // options
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = keys.secretOrKey;
module.exports = passport => {
passport.use(
new JwtStrategy(opts, (jwt_payload, done) => {
User.findById(jwt_payload.id)
.then(user => {
if (user) {
return done(null, user);
}
return done(null, false);
})
.catch(err => console.log("Error in findById\n " + err));
})
);
};
路由器文件user.js包含
// users.js for authentication and authorization
const express = require("express");
const router = express.Router();
const gravatar = require("gravatar");
const bcrypt = require("bcryptjs");
const keys = require("../../config/keys");
const jwt = require("jsonwebtoken");
const passport = require("passport");
// Load User Model to check existing email is used for registration or not?
const User = require("../../models/User");
// @route GET request to api/users/test
// @description Tests users route
// @access Public, without login
router.get("/test", (req, res) => res.json({ msg: "Users Works" }));
// @route GET request to api/users/register
// @description new registration of user.
// @access Public, without login first register
router.post("/register", (req, res) => {
User.findOne({ email: req.body.email }).then(user => {
if (user) {
return res.status(400).json({ email: "Email value exists already." });
} else {
console.log("no user found of this email in DB");
const avatar = gravatar.url(req.body.email, {
s: "200", //Size of gravatar in pixels
r: "pg", //rating,
d: "mm" //default value= 'mm'
});
// create user
const newUser = new User({
name: req.body.name,
email: req.body.email,
avatar,
password: req.body.password
});
// gensalt(noOfSalts_of_Iterations,(err,salt_result)=>{})
bcrypt.genSalt(10, (err, salt) => {
// hash(plaintext,salt,callback(err,resultant ciphertext))
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) {
console.log("error in bcrypt.hash()");
throw err;
}
//assign salted hash to password
newUser.password = hash;
// Save new password in datebase, overriding plaintext;
newUser
.save()
.then(user => res.json(user)) // if yes,then send it as argument in brackets.
.catch(err =>
console.log("Error occured in saving hash password in DB\n")
);
});
});
}
});
});
// @route GET request to api/users/login
// @description Login/signing-in registered user. return JWT token
// @access Public
router.post("/login", (req, res) => {
const email = req.body.email;
const password = req.body.password;
// find user to match it's password
User.findOne({ email: req.body.email }).then(user => {
//check if no user
if (!user) {
return res.status(404).json({ email: "User's email found." });
}
// else if do this..
// if user's email-id is found then match it's password-hash with local-database
bcrypt.compare(password, user.password).then(isMatch => {
if (isMatch) {
// user pswd matched => then return JWT token back for authentication
// res.json({ msg: "Success" });
const payload = { it: user.id, name: user.name, avatar: user.avatar };
// created JWT token
// now sign token
// jwt.sign(payload, secretKey, expire-time, callback );
// jwt.sign
jwt.sign(
payload,
keys.secretOrKey,
{ expiresIn: 3600 },
(err, token) => {
res.json({
success: true,
token: "Bearer " + token
});
}
);
} else {
// pswd doesn't matched
return res.status(400).json({ password: "Password didn't match" });
}
});
});
});
// @route GET request to api/users/current - current user with token
// @description Return current user
// @access Private, can't go without login
router.get(
"/current",
passport.authenticate("jwt", { session: false }),
(req, res) => {
res.json({ msg: "Success" });
}
);
module.exports = router;
控制台没有错误,服务器可以连续运行,但是无法使用标头中发送的令牌进行验证。
我在登录后已生成令牌。
github link进行编码
package.json是
{
"name": "find-geeks",
"version": "1.0.0",
"description": "social media for developers, quite same as Linkedin.",
"main": "server.js",
"scripts": {
"start": "node server.js",
"server": "nodemon server.js"
},
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.18.2",
"express": "^4.16.3",
"gravatar": "^1.6.0",
"jsonwebtoken": "^8.2.0",
"mongoose": "^5.0.12",
"passport": "^0.4.0",
"passport-jwt": "^4.0.0",
"validator": "^9.4.1"
},
"devDependencies": {
"nodemon": "^1.18.3"
}
}