未经授权:错误401 passport-jwt

时间:2017-05-18 11:38:18

标签: javascript node.js authentication

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.
    });

服务类 的 .TS

获取数据。

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);
        });
    });
  }

我这里没有使用授权,只有身份验证。当从服务类调用get时,它会显示未授权。请帮助。

在Authentication.js文件中,我使用了Token:关注你的一些帖子我删除了'JWT'。但是然后显示了401 Unauthorized错误。

请帮忙!

3 个答案:

答案 0 :(得分:0)

在您的服务文件中的headers.append()中要求授权,将其切换到身份验证并查看是否有效

答案 1 :(得分:0)

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

答案 2 :(得分:-1)

你可以试试这个:

server {
       listen         80;
       server_name    my.example.com;
       return         301 https://$server_name$request_uri;
}

server {
       listen         443 ssl;
       server_name    my.example.com;
       # add Strict-Transport-Security to prevent man in the middle attacks
       add_header Strict-Transport-Security "max-age=31536000"; 

       [....]
}