背景描述:
postman在处理经过防御CRSF攻击处理的网站接口时,需要从服务端发来的html中获取 csrf_token 。
需求:
postman 解析接口响应的html文件,从中获取 csrf_token 信息。
实现:
postman 工具提供对html的解析库 [cheerio]
pm.test("获取CsrfToken", function () {
pm.response.to.be.ok;
pm.expect(pm.response.text()).to.include("name=\"token\"");
// 使用cheerio解析html
const $ = cheerio.load(pm.response.text())
// 根据 CsrfToken 标签关键字查找值
pm.collectionVariables.set("CsrfToken", $('input[name=token]').val())
console.log($('input[name=token]').val())
}
)
附:
cheerio 官方文档: https://cheerio.js.org/
csrf(Cross—Site Request Forgery)攻击与防御:https://zhuanlan.zhihu.com/p/114750961
postman 支持的第三方库:https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/#sending-requests-from-scripts