passport.js
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.
});
Service class .ts
to get the data.
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);
});
});
}
I am not using Authorization here, Only Authentication.When call get
post from service class it displays unauthorized.Please help.
In Authentication.js file I have used Token: followed your ans to some post I have removed 'JWT'.But then too 401 Unauthorized error is displayed.
Please help!
via Aditya Jain
No comments:
Post a Comment