简体   繁体   中英

Unauthorized: Error 401 passport-jwt

passport.js

var jwtOptions = {
        jwtFromRequest: ExtractJwt.fromAuthHeader(),
        secretOrKey: config.secret
    }

    var jwtLogin = new JwtStrategy(jwtOptions, function (jwt_payload, done) {
        console.log('payload received', jwt_payload);
        User.findOne(jwt_payload._id, function (err, user) {
            if (err) {
            return done(err, false,{error:'its failed'});
        }
        if (user) {
            return done(null, user);
        }
        else {
            done(null, false,{error:'401'});
        }
    });
});

passport.use(jwtLogin);

Authentication.js

function generateToken(user) {
    return jwt.sign(user, key.secret, {
        expiresIn: '1h',
    });
};

function setUserInfo(request) {
    console.log('inside setUserInfoo', request);
    return {
        _id: request._id,
        email: request.email,

    }
};
exports.login = function (req, res, next) {
    console.log('inside login function');
    var userInfo = setUserInfo(req.user);
    res.status(200).json({
        token: generateToken(userInfo), //removed 'JWT' + generrateToken...Reading your answers.
        user: userInfo
    });
};

routes.js

//Assuming every thing is required correctly.

var requireAuth = passport.authenticate('jwt',{session:false});

 app.use('/api/contacts', contactRoutes);

    contactRoutes.get('/',requireAuth, function(req,res){
        console.log('inside get route of contacts');
        contactControllers.getContacts(req,res)});

    contactRoutes.post('/', requireAuth, function (req, res) {
        console.log("inside post routes of contacts");
        contactControllers.postContacts(req, res); //logic is correct but generate token syntax is similar to login function one.
    });

Service class .ts

to get the data.

getContacts() {
    console.log('Inside getContacts() of service class');
    return new Promise((resolve, reject) => {
      let headers = new Headers();
      headers.append('Authorization', this.auth.token);
      console.log('inside promise');

      this.http.get('http://localhost:8080/api/contacts/', { headers: headers }).map(res =>
        res.json())
        .subscribe(data => {
          resolve(data);
          console.log('inside resolve of service class', data);
        },
        (err) => {
          reject(err);
        });
    });
  }

I am not using Authorization here, Only Authentication.When call get post from service class it displays unauthorized.Please help.

In Authentication.js file I have used Token: followed your ans to some post I have removed 'JWT'.But then too 401 Unauthorized error is displayed.

Please help!

在服务文件中的headers.append()中,请求授权,将其切换为Authentication,看看是否可行

headers.append('Authorization', 'JWT ' + this.auth.token);

您可以尝试以下方法:

headers.append('Authorization', 'Bearer ${this.auth.token}');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM