Issue
I'm new to Node, so i hope for you help... I'm working at MEAN stack app, and trying to implement auth system by passport-jwt. Registration/login forms and pages are working corectly and i can access token and store it in localstorage but when i try to access user profile after login i've got the following Error: 401(Unauthorized).
It seems like im not sending properly the token to the server cuz through postman with token from localstorage everything is working.
Here is my code ..
Error
HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: 'Unauthorized', url: 'http://localhost:3000/users/profile', ok: false, …}
error: "Unauthorized"
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message: "Http failure response for http://localhost:3000/users/profile: 401 Unauthorized"
name: "HttpErrorResponse"
ok: false
status: 401
statusText: "Unauthorized"
url: "http://localhost:3000/users/profile"
Passport.js
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/user');
const config = require('./db.config');
module.exports = function(passport) {
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme("jwt")
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
User.getUserById(jwt_payload._id, (err, user) => {
if(err) {
return done(err, false);
}
if(user) {
return done(null, user);
}
else{
return done(null, false);
}
})
}))
}
Node route.js
router.get('/profile', passport.authenticate('jwt', {session: false}), (req, res, next) => {
res.json({user: req.user})
});
AuthService
getProfile() {
let headers = new HttpHeaders();
this.loadToken();
headers.append('Authorization', this.authToken);
headers.append('Content-Type', 'application/json');
return this.http.get('http://localhost:3000/users/profile', {headers: headers})
.pipe(map((res: any) => res));
}
loadToken() {
const token = localStorage.getItem('id_token');
this.authToken = token;
}
Profile.ts here i call auth service and then getting error
constructor(private auth: AuthService) { }
ngOnInit() {
this.auth.getProfile().subscribe(profile => {
this.user = profile.user;
},
err => {
console.log(err);
return false;
});
}
Thanks in advance :)
Solution
Found the solution.. I spent a lot of time before post this question, so for the people meeted the same problem the best way will be creatiang an interceptor:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const idToken = localStorage.getItem('id_token');
if(idToken) {
const cloned = req.clone({
headers: req.headers.set('Authorization', idToken)
});
return next.handle(cloned)
} else {
return next.handle(req);
}
Answered By - Aleks_thunder
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.