简体   繁体   English

未经授权:错误401 Passport-jwt

[英]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 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 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 服务类别.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. 我不在这里使用授权,仅在身份验证。服务类别中的呼叫get帖子时,它将显示未授权。请提供帮助。

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. 在Authentication.js文件中,我使用了Token:在您的回答之后,我删除了'JWT'。但是随后也会显示401 Unauthorized错误。

Please help! 请帮忙!

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

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

您可以尝试以下方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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