如何使用Axios对接含__RequestVerificationToken的网站完成认证?
解决HomeAccess登录认证失败的问题
你的代码主要有两个核心问题导致认证失败,下面是具体原因和修复方案:
关键问题点
- 未携带关联Cookie:ASP.NET的
__RequestVerificationToken需要和请求返回的对应Cookie配对使用,axios默认不会自动保存和携带Cookie,必须开启withCredentials配置。 - 请求Content-Type不匹配:网站登录表单采用
application/x-www-form-urlencoded格式提交,axios默认会把对象转成JSON格式发送,服务器无法正确解析Payload。
修复后的代码
const axios = require('axios'); const cheerio = require('cheerio'); const qs = require('qs'); // 需要引入qs模块序列化表单数据 // 创建axios实例,统一配置Cookie携带和基础请求头 const instance = axios.create({ withCredentials: true, headers: { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' } }); instance.get('https://homeaccess.katyisd.org/HomeAccess/Account/LogOn') .then((response) => { const $ = cheerio.load(response.data); // 精准定位登录表单内的验证Token const token = $('form[action="/HomeAccess/Account/LogOn"] input[name="__RequestVerificationToken"]').val(); const payload = { __RequestVerificationToken: token, SCKTY00328510CustomEnabled: 'True', SCKTY00436568CustomEnabled: 'True', Database: '10', VerificationOption: 'UsernamePassword', 'LogOnDetails.UserName': 'TestName', tempUN: '', tempPW: '', 'LogOnDetails.Password': 'TestPass' }; // 序列化表单数据并设置正确的Content-Type return instance.post( 'https://homeaccess.katyisd.org/HomeAccess/Account/LogOn', qs.stringify(payload), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } ); }) .then((response) => { // 通过状态码和页面摘要判断登录结果 console.log('登录状态码:', response.status); console.log('返回内容摘要:', response.data.slice(0, 500)); }) .catch((error) => { // 打印详细错误信息方便排查 console.error('请求错误:', error.response?.status, error.response?.data || error.message); });
额外注意事项
- 先执行
npm install qs安装依赖模块。 - 如果仍失败,对比浏览器提交的Payload,检查是否遗漏页面中的其他隐藏字段。
- 若网站拦截非浏览器请求,可在axios实例中添加模拟浏览器的User-Agent请求头,例如:
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
内容的提问来源于stack exchange,提问作者Rapidx
相关产品推荐
相关产品推荐

