jsonwebtoken和express-jwt之间的关系是什么?

时间:2015-08-17 05:34:02

标签: express jwt

以下是使用JWT进行身份验证的典型代码段:

var express = require('express');
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken'); 
var expressJwt = require('express-jwt'); 

var app = express();

var secret = 'top secrect';
var jwtOptions = {algorithm: 'HS256', expiresInMinutes: 1};

// We are going to protect /api routes with JWT
app.use('/api', expressJwt({secret: secret}));

//app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());

app.use('/', express.static(__dirname + '/'));

app.use(function(err, req, res, next) {
    if (err.constructor.name === 'UnauthorizedError') {
        console.log(err);
        res.send(401, 'Unauthorized');
    }
});

app.post('/authenticate', function(req, res) {
    //TODO validate req.body.username and req.body.password
    //if is invalid, return 401
    if (!(req.body.username === 'john.doe' && req.body.password === 'foobar')) {
        res.send(401, 'Wrong user or password');
        return;
    }

    // user object (session data) handled by express-jwt
    var user = {
        session: {
            counter: 0
        },
        first_name: 'John',
        last_name: 'Doe',
        email: 'john@doe.com',
        roles: [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000],
        id: 123
    };

    // We are sending the user inside the token
    var token = jwt.sign(user, secret, jwtOptions);
    res.json({token: token});
});

app.get('/api/restricted', function(req, res) {
    console.log('user ' + req.user.email + ' is calling /api/restricted with roles: ' + req.user.roles);
    var token = '';
    if (req.headers && req.headers.authorization) {
        var parts = req.headers.authorization.split(' ');
        if (parts.length === 2) {
            var scheme = parts[0]
                , credentials = parts[1];

            if (/^Bearer$/i.test(scheme)) {
                token = credentials;
            }
        } else {
            return new UnauthorizedError('credentials_bad_format', {message: 'Format is Authorization: Bearer [token]'});
        }
    } else {
        return new UnauthorizedError('credentials_required', {message: 'No Authorization header was found'});
    }

    // verify token: send by client in Authorization HTTP header
    // 'session timeout' handled by express-jwt (exp value) and throws 401
    jwt.verify(token, secret, jwtOptions, function(err, decoded) {
        if (err)
            return new UnauthorizedError('invalid_token', err);

        req.user = decoded;
        console.log(req.user);
    });

    // update sample data in the session ...
    req.user.session.counter = req.user.session.counter + 10;

    // ... and create new token ...
    var newToken = jwt.sign(req.user, secret, jwtOptions);

    // ... and update in the response HTTP header
    res.header('Authorization', 'Bearer ' + newToken)
    res.json(req.user);
});

app.listen(8080, function() {
    console.log('listening on http://localhost:8080');
});

我想知道为什么要为'/api/resctricted'创建一个处理程序呢?我还没有被app.use('/', express.static(__dirname + '/'));保护吗?

更新 我也查看了express-jwt的源代码,看起来它使用jsonwebtoken.verify()来验证请求中的令牌,这让我感到困惑,为什么要使用{{1}在' / api / restricted'处理程序?

0 个答案:

没有答案