关于node.js:如何使用护照认证更新包含jwt的cookie | 珊瑚贝

How to update cookie containing jwt using passport authentication


我有一个包含签名 jwt 的 cookie,有效期为 5 分钟。 jwt 包含基本用户信息(用于身份验证)以及全局唯一 ID (guid)。如果这些 guid 有效,我会将它们存储在数据库中,并且在 jwt 到期后的下一个请求中,我想:

1.) 检查数据库中的 guid 并查看它是否仍然有效(未列入黑名单)

2.) 使用新的 5 分钟有效期和相同的信息更新 cookie 中的 jwt

我遇到了很多错误,但我尝试过的任何方法都没有奏效,我很好奇这是否可能或目前的正确方法。

我正在使用节点 js 包”passport-jwt”和”jsonwebtoken”来创建 jwt 并验证它们。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//////////////////////
//authorization.js
//////////////////////

const JWTStrategy = require(‘passport-jwt’).Strategy;
const jwt = require(‘jsonwebtoken’);
const mongoose = require(‘mongoose’);

require(‘../models/Guids’);
const Guids = mongoose.model(‘Guids’);

module.exports.JWTStrategy = function (passport) {
    passport.use(‘jwt’, new JWTStrategy({
        jwtFromRequest: req => cookieExtractor(req, ‘token’),
        secretOrKey: ‘secret’,
        passReqToCallback: true
    },
        (req, jwt_payload, done) => {
            if (Date.now() / 1000 > jwt_payload.exp) {
                Guids.findOne({ _id: jwt_payload.guid, userId: jwt_payload.uid })
                    .then(guid => {
                    if (guid.valid) {
                            //REFRESH TOKEN HERE
                            //????????return done(null, jwt_payload);
                        } else {
                            //FORCE USER TO RE-AUTHENTICATE
                            //???????return done(‘access token expired’);
                        }
                })
                .catch(err => {
                    console.log(err);
                    return done(‘failed to validate user’);
                });
            } else {
                return done(null, jwt_payload);
            }
        }
    ));
};

var cookieExtractor = function (req, tokenName) {
    var token = null;
    if (req && req.cookies) {
        token = req.cookies[tokenName];
    } else {
        console.log(‘no cookie found’);
    }
    return token;
};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/////////////////////////////
//app.js
/////////////////////////////
const express = require(‘express’);
const cookieParser = require(‘cookie-parser’);
const bodyParser = require(‘body-parser’);
const passport = require(‘passport’);
const jwt = require(‘jsonwebtoken’);

const app = express();

require(‘./authorization’).JWTStrategy(passport);

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());

//Protected Route
app.get(‘/xyz’, passport.authenticate(‘jwt’, {session: false}),  (req, res) => {
    //route logic….
});

//login Route (creates token)
app.post(‘/login’, (req, res, next) => {
payload = {
    guid: 12345678901010101′,
    uid: ‘123456789’,
};

req.login(payload, { session: false }, (err) => {
    if (err) {
        console.log(err);
    } else {
        const token = jwt.sign(payload, ‘secret’, {expiresIn: ’30s’});
        res.cookie(‘token’, token, { httpOnly: true });
        res.redirect(‘/xyz’);
    };
    }
}

const port = process.env.PORT || 5000;
const server = app.listen(port, () => {
    console.log(`Server started on port ${port}`);
});

默认情况下,当令牌过期时,受保护路由上的身份验证中间件会立即抛出失败。

我想绕过这个失败,而是在”authorization.js”文件中执行一些代码,其中注释为”REFRESH TOKEN HERE”。

由于自动失败,甚至永远无法到达那行代码!我已经尝试过在过期前后进行控制台日志记录。

之前我什至手动绕过了自动失败,但是包含cookie的响应对象(res)在passport-jwt策略中不可用。如果指定的位置由于它是一个中间件功能而无意义,我对应该在哪里实现这个逻辑有点迷茫。

另外,如果受保护的路由是 POST,并且在页面”GET”成功后令牌过期,我不想阻碍 POST 方法。我想无缝刷新令牌,然后与 POST 一起移动。

  • 我不确定我是否理解您使用 GUID 的意图……因为您使用的是什么?如果您不想使用护照发送自定义身份验证消息,您可以使用自定义回调/中间件:function(req, res, next) { passport.authenticate(…)(req, res, next); } 请参阅自定义回调部分中的详细信息
  • @0x1C1B 在我发布的示例中,我硬编码了一个 GUID。在我的实际代码中,我为每个登录 POST 请求生成一个唯一 ID,并将它们存储在数据库中。我会看看自定义回调功能,如果它正常工作,我会回到这篇文章。谢谢
  • @0x1C1B 必须彻底检修我的中间件,但您是对的,自定义回调是正确的方法。如果您做出回复,我会认为您的回复是正确的。非常感谢您将我指向该文档!


Passport 支持自定义消息或更精确的自定义回调。您必须自己手动调用护照身份验证中间件,嵌入到您自己的package中间件中。这允许访问 req 和 res 对象。有关更多详细信息,请参阅文档。

If the built-in options are not sufficient for handling an authentication request, a custom callback can be provided to allow the application to handle success or failure.

1
2
3
4
5
6
7
8
9
10
app.get(‘/login’, function(req, res, next) {
  passport.authenticate(‘local’, function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect(‘/login’); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.redirect(‘/users/’ + user.username);
    });
  })(req, res, next);
});

来源:https://www.codenong.com/54668901/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9408.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?