栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在node.js / express中测试受csrf保护的端点

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在node.js / express中测试受csrf保护的端点

诀窍是您需要将POST测试包装在GET中,并从cookie中解析必要的CSRF令牌。首先,假设您创建了一个与Angular兼容的CSRF
cookie,如下所示:

.use(express.csrf()).use(function (req, res, next) {  res.cookie('XSRF-TOKEN', req.session._csrf);  res.locals.csrftoken = req.session._csrf;  next();})

然后,您的测试可能如下所示:

describe('Authenticated Jade tests', function () {  this.timeout(5000);  before(function (done) {    [Set up an authenticated user here]  });  var validPaths = ['/help', '/products'];  async.each(validPaths, function (path, callback) {    it('should confirm that ' + path + ' serves HTML and is only available when logged in', function (done) {      request.get('https://127.0.0.1:' + process.env.PORT + path, function (err, res, body) {        expect(res.statusCode).to.be(302);        expect(res.headers.location).to.be('/login');        expect(body).to.be('Moved Temporarily. Redirecting to /login');        var csrftoken = unescape(/XSRF-TOKEN=(.*?);/.exec(res.headers['set-cookie'])[1]);        var authAttributes = { _csrf: csrftoken, email: userAttributes.email, password: 'password' };        request.post('https://127.0.0.1:' + process.env.PORT + '/login', { body: authAttributes, json: true }, function (err, res) {          expect(res.statusCode).to.be(303);          request.get('https://127.0.0.1:' + process.env.PORT + path, function (err, res, body) { expect(res.statusCode).to.be(200); expect(body.toString().substr(-14)).to.be('</body></html>'); request.get('https://127.0.0.1:' + process.env.PORT + '/bye', function () {   done(); });          });        });      });    });    callback();  });});

这个想法是实际登录并使用您从cookie获得的CSRF令牌。请注意,您需要在mocha测试文件的顶部执行以下操作:

var request = require('request').defaults({jar: true, followRedirect: false});


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/448296.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号