345 lines
11 KiB
JavaScript
345 lines
11 KiB
JavaScript
const axios = require('axios');
|
|
const CryptoJS = require('crypto-js');
|
|
const NodeRSA = require('node-rsa');
|
|
|
|
// 配置信息
|
|
const CONFIG = {
|
|
BASE_URL: 'http://localhost/dev-api',
|
|
LOGIN_ENDPOINT: '/auth/login',
|
|
CLIENT_ID: 'e5cd7e4891bf95d1d19206ce24a7b32e',
|
|
TENANT_ID: '000000',
|
|
REFERER: 'http://localhost/login?redirect=%252Findex',
|
|
// RSA公钥
|
|
RSA_PUBLIC_KEY:
|
|
'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKoR8mX0rGKLqzcWmOzbfj64K8ZIgOdHnzkXSOVOZbFu/TJhZ7rFAN+eaGkl3C4buccQd/EjEsj9ir7ijT7h96MCAwEAAQ==',
|
|
};
|
|
|
|
// 默认登录凭据
|
|
const CREDENTIALS = {
|
|
username: 'admin',
|
|
password: 'admin123',
|
|
};
|
|
|
|
/**
|
|
* 生成随机AES密钥
|
|
*/
|
|
function generateRandomAESKey(length = 32) {
|
|
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
|
let result = '';
|
|
for (let i = 0; i < length; i++) {
|
|
result += characters.charAt(Math.floor(Math.random() * characters.length));
|
|
}
|
|
return result;
|
|
}
|
|
|
|
/**
|
|
* AES加密数据
|
|
*/
|
|
function encryptWithAES(data, key) {
|
|
const keyUtf8 = CryptoJS.enc.Utf8.parse(key);
|
|
const encrypted = CryptoJS.AES.encrypt(data, keyUtf8, {
|
|
mode: CryptoJS.mode.ECB,
|
|
padding: CryptoJS.pad.Pkcs7,
|
|
});
|
|
return encrypted.toString();
|
|
}
|
|
|
|
/**
|
|
* RSA加密AES密钥
|
|
*/
|
|
function encryptAESKeyWithRSA(aesKey) {
|
|
try {
|
|
const pemKey = `-----BEGIN PUBLIC KEY-----\n${CONFIG.RSA_PUBLIC_KEY}\n-----END PUBLIC KEY-----`;
|
|
const rsaKey = new NodeRSA(pemKey);
|
|
rsaKey.setOptions({ encryptionScheme: 'pkcs1' });
|
|
|
|
// 将AES密钥转为Base64
|
|
const aesKeyBase64 = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(aesKey));
|
|
|
|
// RSA加密
|
|
return rsaKey.encrypt(aesKeyBase64, 'base64');
|
|
} catch (error) {
|
|
console.error('RSA加密失败:', error.message);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 自定义Header登录 - 按照用户要求
|
|
*/
|
|
async function customHeaderLogin(credentials = CREDENTIALS) {
|
|
console.log('🔐 开始自定义Header登录...');
|
|
console.log('📍 接口地址:', CONFIG.BASE_URL + CONFIG.LOGIN_ENDPOINT);
|
|
|
|
try {
|
|
// 1. 生成AES密钥
|
|
const aesKey = generateRandomAESKey(32);
|
|
console.log('🔑 生成AES密钥:', aesKey);
|
|
|
|
// 2. 准备登录数据
|
|
const loginData = {
|
|
tenantId: CONFIG.TENANT_ID,
|
|
username: credentials.username,
|
|
password: credentials.password,
|
|
clientId: CONFIG.CLIENT_ID,
|
|
grantType: 'password',
|
|
};
|
|
|
|
console.log('📋 登录数据:', JSON.stringify(loginData, null, 2));
|
|
|
|
// 3. AES加密登录数据
|
|
const encryptedData = encryptWithAES(JSON.stringify(loginData), aesKey);
|
|
console.log('🔐 AES加密后数据长度:', encryptedData.length);
|
|
|
|
// 4. RSA加密AES密钥
|
|
const encryptedKey = encryptAESKeyWithRSA(aesKey);
|
|
if (!encryptedKey) {
|
|
throw new Error('RSA加密AES密钥失败');
|
|
}
|
|
console.log('🔑 RSA加密后密钥长度:', encryptedKey.length);
|
|
|
|
// 5. 按照用户要求设置Header
|
|
const headers = {
|
|
'Content-Type': 'application/json;charset=utf-8',
|
|
clientid: CONFIG.CLIENT_ID, // 用户要求的clientid
|
|
'encrypt-key': encryptedKey, // 用户要求的encrypt-key
|
|
referer: CONFIG.REFERER, // 用户要求的referer
|
|
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
|
|
isToken: 'false',
|
|
isEncrypt: 'true',
|
|
repeatSubmit: 'false',
|
|
};
|
|
|
|
console.log('📤 请求头设置:');
|
|
console.log(' - clientid:', headers.clientid);
|
|
console.log(' - encrypt-key:', encryptedKey.substring(0, 50) + '...');
|
|
console.log(' - referer:', headers.referer);
|
|
console.log(' - Content-Type:', headers['Content-Type']);
|
|
|
|
// 6. 发送登录请求
|
|
console.log('\n🚀 发送登录请求...');
|
|
const response = await axios.post(CONFIG.BASE_URL + CONFIG.LOGIN_ENDPOINT, encryptedData, {
|
|
headers: headers,
|
|
timeout: 10000,
|
|
});
|
|
|
|
// 7. 处理响应
|
|
console.log('✅ 请求成功!');
|
|
console.log('📊 响应状态:', response.status);
|
|
console.log('📄 响应数据:', JSON.stringify(response.data, null, 2));
|
|
|
|
// 8. 提取Token
|
|
if (response.data.code === 200 && response.data.data?.access_token) {
|
|
const token = response.data.data.access_token;
|
|
console.log('\n🎯 成功获取Token!');
|
|
console.log('🎫 Token:', token);
|
|
console.log('🎫 Token长度:', token.length);
|
|
console.log('🎫 Token前50字符:', token.substring(0, 50) + '...');
|
|
|
|
// 测试Token有效性
|
|
await testTokenValidity(token);
|
|
|
|
return {
|
|
success: true,
|
|
token: token,
|
|
data: response.data,
|
|
};
|
|
} else {
|
|
console.log('⚠️ 登录请求成功,但未获取到Token');
|
|
console.log('❌ 错误信息:', response.data.msg);
|
|
return {
|
|
success: false,
|
|
error: response.data.msg || 'Unknown error',
|
|
data: response.data,
|
|
};
|
|
}
|
|
} catch (error) {
|
|
console.log('❌ 登录失败!');
|
|
|
|
if (error.response) {
|
|
console.log('📊 错误状态码:', error.response.status);
|
|
console.log('📄 错误响应:', JSON.stringify(error.response.data, null, 2));
|
|
|
|
// 特殊错误处理
|
|
if (error.response.status === 500) {
|
|
console.log('💡 提示: 这可能是服务器端加密处理问题');
|
|
} else if (error.response.status === 403) {
|
|
console.log('💡 提示: 这是权限配置问题,需要联系管理员');
|
|
}
|
|
} else if (error.request) {
|
|
console.log('🌐 网络错误,请检查服务器是否启动');
|
|
console.log('📡 请求详情:', error.message);
|
|
} else {
|
|
console.log('⚙️ 请求配置错误:', error.message);
|
|
}
|
|
|
|
return {
|
|
success: false,
|
|
error: error.response?.data || error.message,
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 测试Token有效性
|
|
*/
|
|
async function testTokenValidity(token) {
|
|
console.log('\n🧪 测试Token有效性...');
|
|
|
|
try {
|
|
const response = await axios.get(CONFIG.BASE_URL + '/system/user/getInfo', {
|
|
headers: {
|
|
Authorization: `Bearer ${token}`,
|
|
clientid: CONFIG.CLIENT_ID,
|
|
referer: CONFIG.REFERER,
|
|
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
|
|
},
|
|
timeout: 10000,
|
|
});
|
|
|
|
console.log('✅ Token有效! 用户信息获取成功');
|
|
console.log('👤 用户信息:', JSON.stringify(response.data, null, 2));
|
|
return true;
|
|
} catch (error) {
|
|
console.log('❌ Token测试失败');
|
|
if (error.response) {
|
|
console.log('📊 错误状态码:', error.response.status);
|
|
console.log('📄 错误信息:', error.response.data);
|
|
} else {
|
|
console.log('🌐 网络错误:', error.message);
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 标准非加密登录 (备用方案)
|
|
*/
|
|
async function standardLogin(credentials = CREDENTIALS) {
|
|
console.log('\n🔓 尝试标准非加密登录 (备用方案)...');
|
|
|
|
const loginData = {
|
|
tenantId: CONFIG.TENANT_ID,
|
|
username: credentials.username,
|
|
password: credentials.password,
|
|
clientId: CONFIG.CLIENT_ID,
|
|
grantType: 'password',
|
|
};
|
|
|
|
const headers = {
|
|
'Content-Type': 'application/json;charset=utf-8',
|
|
clientid: CONFIG.CLIENT_ID,
|
|
referer: CONFIG.REFERER,
|
|
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
|
|
};
|
|
|
|
try {
|
|
const response = await axios.post(CONFIG.BASE_URL + CONFIG.LOGIN_ENDPOINT, loginData, {
|
|
headers,
|
|
timeout: 10000,
|
|
});
|
|
|
|
console.log('✅ 标准登录请求成功');
|
|
console.log('📄 响应数据:', JSON.stringify(response.data, null, 2));
|
|
|
|
if (response.data.code === 200 && response.data.data?.access_token) {
|
|
const token = response.data.data.access_token;
|
|
console.log('🎫 获取到Token:', token.substring(0, 50) + '...');
|
|
return { success: true, token: token, data: response.data };
|
|
} else {
|
|
return { success: false, error: response.data.msg, data: response.data };
|
|
}
|
|
} catch (error) {
|
|
console.log('❌ 标准登录失败');
|
|
if (error.response) {
|
|
console.log('📊 状态码:', error.response.status);
|
|
console.log('📄 错误信息:', error.response.data);
|
|
}
|
|
return { success: false, error: error.response?.data || error.message };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 主函数 - 智能登录策略
|
|
*/
|
|
async function smartLogin(credentials) {
|
|
console.log('🌟'.repeat(25));
|
|
console.log('🚀 智能登录脚本 - 自定义Header版本');
|
|
console.log('🌟'.repeat(25));
|
|
|
|
let result = null;
|
|
|
|
// 策略1: 首先尝试加密登录
|
|
console.log('\n📋 策略1: 尝试加密登录 (用户指定Header格式)');
|
|
result = await customHeaderLogin(credentials);
|
|
|
|
if (result.success) {
|
|
console.log('\n🎉 加密登录成功!');
|
|
return result;
|
|
}
|
|
|
|
// 策略2: 如果加密登录失败,尝试标准登录
|
|
console.log('\n📋 策略2: 尝试标准非加密登录 (备用方案)');
|
|
result = await standardLogin(credentials);
|
|
|
|
if (result.success) {
|
|
console.log('\n🎉 标准登录成功!');
|
|
return result;
|
|
}
|
|
|
|
// 所有策略都失败
|
|
console.log('\n❌ 所有登录策略都失败了');
|
|
console.log('🔧 建议检查:');
|
|
console.log(' 1. 服务器是否正常运行');
|
|
console.log(' 2. 用户权限是否正确配置');
|
|
console.log(' 3. 网络连接是否正常');
|
|
|
|
return result;
|
|
}
|
|
|
|
// 导出函数
|
|
module.exports = {
|
|
customHeaderLogin,
|
|
standardLogin,
|
|
testTokenValidity,
|
|
smartLogin,
|
|
CONFIG,
|
|
CREDENTIALS,
|
|
};
|
|
|
|
// 直接运行脚本
|
|
if (require.main === module) {
|
|
console.log('🔥 检查依赖包...');
|
|
|
|
// 检查依赖
|
|
try {
|
|
require('axios');
|
|
require('crypto-js');
|
|
require('node-rsa');
|
|
console.log('✅ 所有依赖包检查完成');
|
|
} catch (error) {
|
|
console.error('❌ 缺少依赖包,请运行: npm install axios crypto-js node-rsa');
|
|
process.exit(1);
|
|
}
|
|
|
|
// 运行智能登录
|
|
smartLogin(CREDENTIALS)
|
|
.then((result) => {
|
|
console.log('\n' + '🌟'.repeat(25));
|
|
console.log('📊 最终结果:');
|
|
if (result.success) {
|
|
console.log('✅ 登录成功!');
|
|
console.log('🎫 Token:', result.token);
|
|
console.log('💡 您可以使用这个Token进行后续API调用');
|
|
} else {
|
|
console.log('❌ 登录失败!');
|
|
console.log('📄 错误信息:', result.error);
|
|
}
|
|
console.log('🌟'.repeat(25));
|
|
})
|
|
.catch((error) => {
|
|
console.error('💥 脚本运行出错:', error.message);
|
|
process.exit(1);
|
|
});
|
|
}
|