After successfully logging in I am getting the jwt token, now to access restricted api's I am sending the authorization header, but I am always getting
401 Unauthorized
I have referred to this Authenticating node API with passport-jwt question asked here but didn't helped me,
this is the function I am calling for accessing data from resticted api
check() {
console.log(this.token);
var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append("Authorization", "Bearer" + this.token);
let url = this.authenticationEndPoint + 'random';
this.checkauth(url, headers).subscribe(
data => {
console.log(data);
},
error => {
console.log("error");
}
);
}
checkauth(url:string, header:any): Observable<any> {
return this.http.get(url, header)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res;
return body || {};
}
On my server in nodeJs here is the login code sending the jwt token:
app.post('/login_mobile', function(req, res) {
if(!(req.body.email && req.body.passpord)) {
user.findOne({'local.email' : req.body.email}, function(err, user) {
if (err) { return done(err);}
if (!user) {
return res.json(200, "email is wrong");
}
if(!user.validPassword(req.body.password)) {
return res.json(200, "wrong password");
}
var token = jwt.encode(user, configAuth.secret);
return res.json(200, { user: user, jwtToken: token });
});
}
else {
res.send("no credentials provided");
}
});
code for responding to restricted api request
app.get('/random', passport.authenticate('jwt', { session: false }),
function(req, res) {
res.send("success");
});
this is the passport strategy I am using to authenticate user, but strangely it is not even printing here still it is sending 401 status.
var opts = {};
opts.secretOrKey = configAuth.secret;
opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
passport.use(new JwtStrategy(opts, function(jwt_payload, done){
console.log("here");
console.log(jwt_payload);
User.findOne({_id: jwt_payload._id}, function(err, found_user) {
if (err) {
return done(err, false);
}
if(found_user !== null) {
res.send("finally");
}
else {
res.send("authentication failed");
}
return found_user ? done(null, found_user) : done(null, false);
})
}));
If someone can please point out my mistake.