简体   繁体   English

护照 JWT - 未经授权

[英]Passport JWT - Unauthorized

I'm having a problem where its always returning unauthorized for me.我遇到了一个问题,它总是未经授权返回给我。 When i set the header Authorization to the token that received.当我将 header 授权设置为收到的令牌时。 It returns back with.它返回。

Unauthorized未经授权

. .

router.get('/dashboard', passport.authenticate('jwt', {session: false}), (req, res) => {

    res.json('It worked: User ID is: ' + req.user._id);

});

. .

var jwtOptions = {

    jwtFromRequest: ExtractJwt.fromAuthHeader(),
    secretOrKey: config.jwt.secretOrKey
    //issuer: config.jwt.issuer,
    //audience: config.jwt.audience,
};

passport.use(new JWTStrategy(jwtOptions, (jwt_payload, done) => {

    User.findOne({id: jwt_payload.id}, (err, user) => {

        if (err) {
            return done(err, false);
        }

        if (!user) {
            return done(null, false);
        }

        return done(null, user);

    });

}));

You have to change these things:你必须改变这些事情:

1) You have to change jwtFromRequest: ExtractJwt.fromAuthHeader(), to jwtFromRequest :ExtractJwt.fromAuthHeaderAsBearerToken(), 1)您必须将jwtFromRequest: ExtractJwt.fromAuthHeader(),更改为jwtFromRequest :ExtractJwt.fromAuthHeaderAsBearerToken(),

2) Set the header: Authorization:Bearer {token} 2)设置头部: Authorization:Bearer {token}

3) jwt_payload._id change to jwt_payload._doc._id 3) jwt_payload._id改为jwt_payload._doc._id

I was experiencing the same problem!我遇到了同样的问题! The code below worked for me.下面的代码对我有用。

module.exports = function(passport) {
    passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
        User.findById(jwt_payload._id, function(err, user) {
            if (err) {
                return done(err, false);
            }
            if (user) {
                done(null, user);
            } else {
                done(null, false);
            }
        });
    }));
};

The problem lies with User.findOne({id: jwt_payload.id}, ...问题在于User.findOne({id: jwt_payload.id}, ...

Also while attaching the token to the header use the 'beforeSend' in the AJAX call in this format:此外,在将令牌附加到标头时,请在 AJAX 调用中以这种格式使用“beforeSend”:

$.ajax({
        url:  url,
        type: 'POST',
        data: data,
        beforeSend: function(xhr) {
          xhr.setRequestHeader('Authorization', window.localStorage.getItem('token'));
        },
        success: function(data) {
          console.log(data);
        },
        error: console.log("Error");
});

You probably must have made a mistake in the request header .您可能在request header犯了错误。 As per the README , it should be 'Authorization' = 'bearer token_received_on_login'根据自述文件,它应该是'Authorization' = 'bearer token_received_on_login'

只需要进行一项更改,使用jwt_payload._doc.id而不是jwt_payload.id

VS code server hangup this will happen because of some mistakes in your code. VS 代码服务器挂断这会发生,因为您的代码中存在一些错误。 its not specific to any common code change.它不特定于任何常见的代码更改。 It can be any of the small code mistakes done by you.它可能是您犯的任何小代码错误。 In my case i was using就我而言,我正在使用

app.use(express.json)

instead of而不是

app.use(express.json())

In my case that was not using the same secret value to sign and extract the jwt. After setting the same secret value to both scenarios authentication worked like a charm.在我的例子中,没有使用相同的秘密值来签名和提取 jwt。在为两种情况设置相同的秘密值后,身份验证就像一个魅力。

when creating the jwt using jsonwebtoken npm package使用 jsonwebtoken 创建 jwt 时 npm package

const token = jwt.sign(payload, process.env.SECRET, { expiresIn: "1d" })
        return res.status(200).send({
            success: true,
            message: "Logged in successfully!",
            token: "Bearer " + token
        })

When extracting the jwt inside passport提取护照里面的jwt时

const opts = {
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: process.env.SECRET
};

passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
    console.log("jwt_payload", jwt_payload)
    UserModel.findOne({ id: jwt_payload.id }, function(err, user) {
        if (err) {
            return done(err, false);
        }
        if (user) {
            return done(null, user);
        } else {
            return done(null, false);
            // or you could create a new account
        }
    });
}));

In my case: it was the algorithms就我而言:这是算法

const options = {
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey: PUB_KEY,
  algorithms: ['RS256']
};

I removed "algorithms: ['RS256']" and it worked (feeling a bit dum for solving that in 2 hours)我删除了“算法:['RS256']”并且它起作用了(在 2 小时内解决这个问题感觉有点笨拙)

  1. Set the header from res.json({token: 'JWT ' + token}) to res.json({token: 'Bearer ' + token})将头从res.json({token: 'JWT ' + token})res.json({token: 'Bearer ' + token})

  2. jwt_payload.data._id worked for me jwt_payload.data._id为我工作

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

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