passport.js未經授權:錯誤401護照,智威湯遜
var jwtOptions = {
jwtFromRequest: ExtractJwt.fromAuthHeader(),
secretOrKey: config.secret
}
var jwtLogin = new JwtStrategy(jwtOptions, function (jwt_payload, done) {
console.log('payload received', jwt_payload);
User.findOne(jwt_payload._id, function (err, user) {
if (err) {
return done(err, false,{error:'its failed'});
}
if (user) {
return done(null, user);
}
else {
done(null, false,{error:'401'});
}
});
});
passport.use(jwtLogin);
Authentication.js
function generateToken(user) {
return jwt.sign(user, key.secret, {
expiresIn: '1h',
});
};
function setUserInfo(request) {
console.log('inside setUserInfoo', request);
return {
_id: request._id,
email: request.email,
}
};
exports.login = function (req, res, next) {
console.log('inside login function');
var userInfo = setUserInfo(req.user);
res.status(200).json({
token: generateToken(userInfo), //removed 'JWT' + generrateToken...Reading your answers.
user: userInfo
});
};
routes.js
//Assuming every thing is required correctly.
var requireAuth = passport.authenticate('jwt',{session:false});
app.use('/api/contacts', contactRoutes);
contactRoutes.get('/',requireAuth, function(req,res){
console.log('inside get route of contacts');
contactControllers.getContacts(req,res)});
contactRoutes.post('/', requireAuth, function (req, res) {
console.log("inside post routes of contacts");
contactControllers.postContacts(req, res); //logic is correct but generate token syntax is similar to login function one.
});
服務類 .ts
獲取數據。
getContacts() {
console.log('Inside getContacts() of service class');
return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('Authorization', this.auth.token);
console.log('inside promise');
this.http.get('http://localhost:8080/api/contacts/', { headers: headers }).map(res =>
res.json())
.subscribe(data => {
resolve(data);
console.log('inside resolve of service class', data);
},
(err) => {
reject(err);
});
});
}
我不使用授權這裏
,只有Authentication.When調用從服務類get
後它會顯示unauthorized.Please幫助。
在Authentication.js文件中,我已經使用了Token:跟隨你的ans到了一些帖子,我已經刪除了'JWT'。但是那時也會顯示401未經授權的錯誤。
請幫忙!
如果你真的想得到幫助,你應該把你的問題更多的細節。例如:'console.log'輸出和你的頭文件中的一個轉儲。 –