| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164 |
- const axios = require('axios');
- const CryptoJS = require('crypto-js');
- const NodeRSA = require('node-rsa');
- /**
- * 🚀 快速Token获取器
- * 按照用户指定的Header格式进行登录获取Token
- */
- // 配置
- const CONFIG = {
- url: 'http://localhost/dev-api/auth/login',
- clientId: 'e5cd7e4891bf95d1d19206ce24a7b32e',
- tenantId: '000000',
- referer: 'http://localhost/login?redirect=%252Findex',
- rsaKey: 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKoR8mX0rGKLqzcWmOzbfj64K8ZIgOdHnzkXSOVOZbFu/TJhZ7rFAN+eaGkl3C4buccQd/EjEsj9ir7ijT7h96MCAwEAAQ==',
- };
- // 登录凭据
- const CREDENTIALS = {
- username: 'admin',
- password: 'admin123',
- };
- /**
- * 快速获取Token
- */
- async function getToken(username = CREDENTIALS.username, password = CREDENTIALS.password) {
- try {
- console.log('🔑 正在获取Token...');
- // 1. 生成AES密钥
- const aesKey = generateAESKey();
- // 2. 准备数据
- const data = {
- tenantId: CONFIG.tenantId,
- username: username,
- password: password,
- clientId: CONFIG.clientId,
- grantType: 'password',
- };
- // 3. 加密数据
- const encryptedData = aesEncrypt(JSON.stringify(data), aesKey);
- const encryptedKey = rsaEncrypt(aesKey);
- // 4. 设置Header
- const headers = {
- 'Content-Type': 'application/json;charset=utf-8',
- clientid: CONFIG.clientId,
- 'encrypt-key': encryptedKey,
- referer: CONFIG.referer,
- 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
- isToken: 'false',
- isEncrypt: 'true',
- repeatSubmit: 'false',
- };
- // 5. 发送请求
- const response = await axios.post(CONFIG.url, encryptedData, { headers, timeout: 10000 });
- // 6. 返回Token
- if (response.data.code === 200 && response.data.data?.access_token) {
- const token = response.data.data.access_token;
- console.log('✅ Token获取成功!');
- console.log('🎫 Token:', token);
- return token;
- } else {
- throw new Error(response.data.msg || 'Unknown error');
- }
- } catch (error) {
- console.error('❌ 获取Token失败:', error.response?.data?.msg || error.message);
- return null;
- }
- }
- /**
- * 生成AES密钥
- */
- function generateAESKey() {
- const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
- let result = '';
- for (let i = 0; i < 32; i++) {
- result += chars.charAt(Math.floor(Math.random() * chars.length));
- }
- return result;
- }
- /**
- * AES加密
- */
- function aesEncrypt(data, key) {
- const keyUtf8 = CryptoJS.enc.Utf8.parse(key);
- return CryptoJS.AES.encrypt(data, keyUtf8, {
- mode: CryptoJS.mode.ECB,
- padding: CryptoJS.pad.Pkcs7,
- }).toString();
- }
- /**
- * RSA加密
- */
- function rsaEncrypt(aesKey) {
- const pemKey = `-----BEGIN PUBLIC KEY-----\n${CONFIG.rsaKey}\n-----END PUBLIC KEY-----`;
- const rsaKey = new NodeRSA(pemKey);
- rsaKey.setOptions({ encryptionScheme: 'pkcs1' });
- const aesKeyBase64 = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(aesKey));
- return rsaKey.encrypt(aesKeyBase64, 'base64');
- }
- /**
- * 使用Token调用API示例
- */
- async function callAPIWithToken(token, apiPath) {
- try {
- const response = await axios.get(`http://localhost/dev-api${apiPath}`, {
- headers: {
- Authorization: `Bearer ${token}`,
- clientid: CONFIG.clientId,
- referer: CONFIG.referer,
- 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
- },
- timeout: 10000,
- });
- return response.data;
- } catch (error) {
- console.error('API调用失败:', error.response?.data?.msg || error.message);
- return null;
- }
- }
- // 导出函数
- module.exports = {
- getToken,
- callAPIWithToken,
- CONFIG,
- CREDENTIALS,
- };
- // 直接运行
- if (require.main === module) {
- console.log('🚀 快速Token获取器');
- console.log('='.repeat(40));
- getToken().then(async (token) => {
- if (token) {
- console.log('\n💡 使用示例:');
- console.log(`const token = "${token.substring(0, 50)}...";`);
- console.log('// 使用这个Token调用其他API');
- // 示例:获取用户信息
- console.log('\n🧪 测试API调用...');
- const userInfo = await callAPIWithToken(token, '/system/user/getInfo');
- if (userInfo && userInfo.code === 200) {
- console.log('✅ API调用成功! 用户:', userInfo.data.user.nickName);
- }
- console.log('\n='.repeat(40));
- console.log('🎯 Token已保存到变量中,可以直接使用!');
- }
- });
- }
|