Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

776
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda