Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

773
Views
NodeJs :Error 401(Unauthorized), passport, jwt. MEAN stack, node, express, angular, mongoose

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 :)

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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);
    }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!