Passport JWT Unauthorized in node js and angular

Discussão em 'Angular' iniciado por Prasad Gavande, Março 5, 2025.

  1. I am using passport jwt with node and Angular. it is throwing unauthorized error.

    I have tried with many solution on other stackoverflow questions but nothing works.

    Below is my passport implementation.

    require('dotenv').config()
    const user = require('../models/user');

    const SECRET = process.env.REFRESH_TOKEN_SECRET;
    const { Strategy, ExtractJwt } = require('passport-jwt');

    const options = {
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: SECRET
    }

    module.exports = (passport) => {
    passport.use(new Strategy(options, async (payload, done) => {
    await user.findByPk(payload.userId).then(user => {
    if (user) {
    return done(null, user);
    }
    return done(null, false);
    }).catch(error => {
    return done(null, error);
    });
    }));
    }


    In app.js, I have added passport as below.

    app.use(passport.initialize());
    require("./middleware/passport")(passport);


    I have other middleware called auth.js where I have created userAuth function as below

    exports.userAuth = passport.authenticate("jwt", { session: false });

    and in routing, I am just passing userAuth middleware as below

    router.get(
    '/categories',
    userAuth,
    checkRole(['admin', 'superadmin']),
    categoryController.getAllCategories
    );


    for Authorization, I have implemented interceptor in Angular application, below is interceptor implementation

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // add authorization header with jwt token if available
    let currentUser = this.authenticationService.currentUserValue;
    if (currentUser && currentUser.token) {
    request = request.clone({
    setHeaders: {
    Authorization: `Bearer ${currentUser.token}`
    }
    });
    }

    return next.handle(request);
    }


    Why it is throwing unauthorized? am I doing something wrong?

    Continue reading...

Compartilhe esta Página