2017-01-20 3 views
8

私はトークンの有無にかかわらずルータにアクセスできます。ユーザーがトークンを持っている場合は、私にこのようreq.userトークンの有無にかかわらず使用可能なルートJWT + PASSPORT

与えるより:

router.get('/profile', function(req, res) { 
if(req.user) { // or if (req.isAuthenticated()) 
res.send('logged') 
} else { 
res.send('not loggedIn') 
} 
}); 

マイアプリ:私はトークンなし/profileにアクセスしようとした場合

var JwtStrategy = require('passport-jwt').Strategy, 
ExtractJwt = require('passport-jwt').ExtractJwt; 
var opts = {} 
opts.jwtFromRequest = ExtractJwt.fromAuthHeader(); 
opts.secretOrKey = 'sh'; 
passport.use(new JwtStrategy(opts, function(jwt_payload, done) { 
User.findOne({id: jwt_payload.sub}, function(err, user) { 
    if (err) { 
     return done(err, false); 
    } 
    if (user) { 
     done(null, user); 
    } else { 
     done(null, false); 
     // or you could create a new account 
    } 
}); 
})); 

を、正常に動作します。私もトークンなしでそれにアクセスしたいと、私はTOKEを提供している場合、私のユーザーを与えるヘッダー内のトークンとアクセス/profileしようが私にnot loggedIn

を与える しかし、。

ps:すでにpassport.authenticate('jwt')を使用してテストされています。私がトークンを与えれば私にアクセスさせてください。

答えて

2

あなたが要求オブジェクトがユーザー属性を持っていない要求データに

if (req.params.user) {do something...} 

または

if (req.body.user) {do something...} 

にアクセスするには、以下のいずれかを使用する必要があります

router.get('/profile', authenticateUser(), profile()); 

function authenticateUser(req, res, next) { 
    // your strategy here... 
    if (authenticated) { 
    req.user = user; 
    next(); 
    } else { 
    return res.status(401).send("Not authenticated"); 
    } 
} 

function profile(req, res, next) { 
    var userId = req.user.id; 
    User.findById(userId, function(err, user) { 
    if (err) { return res.status(500).json(err); } 
    return res.json(user); 
    }) 
} 
2

を次のようにルータを変更。

0

これは、私はそれをやっている方法です:

const passport = require('passport'); 

const optionalJwt = function (req, res, next) { 
    if (req.headers['authorization']) { 
    return passport.authenticate('jwt', { session: false })(req, res, next); 
    } 
    return next(); 
}; 

app.get('/my/route', optionalJwt, function (req, res, next) { 
    if (req.isAuthenticated()) { 
    res.send('My name is ' + req.user.name); 
    } else { 
    res.send('I\'m not authenticated :('); 
    } 
}); 

認証ヘッダが含まれているが、トークンの有効期限が切れているか、それは無効だが、それは目的を果たす可能性がある場合、それはまだ失敗します。私のためにそれはしました。

関連する問題