quick-token-getter.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. const axios = require('axios');
  2. const CryptoJS = require('crypto-js');
  3. const NodeRSA = require('node-rsa');
  4. /**
  5. * 🚀 快速Token获取器
  6. * 按照用户指定的Header格式进行登录获取Token
  7. */
  8. // 配置
  9. const CONFIG = {
  10. url: 'http://localhost/dev-api/auth/login',
  11. clientId: 'e5cd7e4891bf95d1d19206ce24a7b32e',
  12. tenantId: '000000',
  13. referer: 'http://localhost/login?redirect=%252Findex',
  14. rsaKey: 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKoR8mX0rGKLqzcWmOzbfj64K8ZIgOdHnzkXSOVOZbFu/TJhZ7rFAN+eaGkl3C4buccQd/EjEsj9ir7ijT7h96MCAwEAAQ==',
  15. };
  16. // 登录凭据
  17. const CREDENTIALS = {
  18. username: 'admin',
  19. password: 'admin123',
  20. };
  21. /**
  22. * 快速获取Token
  23. */
  24. async function getToken(username = CREDENTIALS.username, password = CREDENTIALS.password) {
  25. try {
  26. console.log('🔑 正在获取Token...');
  27. // 1. 生成AES密钥
  28. const aesKey = generateAESKey();
  29. // 2. 准备数据
  30. const data = {
  31. tenantId: CONFIG.tenantId,
  32. username: username,
  33. password: password,
  34. clientId: CONFIG.clientId,
  35. grantType: 'password',
  36. };
  37. // 3. 加密数据
  38. const encryptedData = aesEncrypt(JSON.stringify(data), aesKey);
  39. const encryptedKey = rsaEncrypt(aesKey);
  40. // 4. 设置Header
  41. const headers = {
  42. 'Content-Type': 'application/json;charset=utf-8',
  43. clientid: CONFIG.clientId,
  44. 'encrypt-key': encryptedKey,
  45. referer: CONFIG.referer,
  46. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
  47. isToken: 'false',
  48. isEncrypt: 'true',
  49. repeatSubmit: 'false',
  50. };
  51. // 5. 发送请求
  52. const response = await axios.post(CONFIG.url, encryptedData, { headers, timeout: 10000 });
  53. // 6. 返回Token
  54. if (response.data.code === 200 && response.data.data?.access_token) {
  55. const token = response.data.data.access_token;
  56. console.log('✅ Token获取成功!');
  57. console.log('🎫 Token:', token);
  58. return token;
  59. } else {
  60. throw new Error(response.data.msg || 'Unknown error');
  61. }
  62. } catch (error) {
  63. console.error('❌ 获取Token失败:', error.response?.data?.msg || error.message);
  64. return null;
  65. }
  66. }
  67. /**
  68. * 生成AES密钥
  69. */
  70. function generateAESKey() {
  71. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  72. let result = '';
  73. for (let i = 0; i < 32; i++) {
  74. result += chars.charAt(Math.floor(Math.random() * chars.length));
  75. }
  76. return result;
  77. }
  78. /**
  79. * AES加密
  80. */
  81. function aesEncrypt(data, key) {
  82. const keyUtf8 = CryptoJS.enc.Utf8.parse(key);
  83. return CryptoJS.AES.encrypt(data, keyUtf8, {
  84. mode: CryptoJS.mode.ECB,
  85. padding: CryptoJS.pad.Pkcs7,
  86. }).toString();
  87. }
  88. /**
  89. * RSA加密
  90. */
  91. function rsaEncrypt(aesKey) {
  92. const pemKey = `-----BEGIN PUBLIC KEY-----\n${CONFIG.rsaKey}\n-----END PUBLIC KEY-----`;
  93. const rsaKey = new NodeRSA(pemKey);
  94. rsaKey.setOptions({ encryptionScheme: 'pkcs1' });
  95. const aesKeyBase64 = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(aesKey));
  96. return rsaKey.encrypt(aesKeyBase64, 'base64');
  97. }
  98. /**
  99. * 使用Token调用API示例
  100. */
  101. async function callAPIWithToken(token, apiPath) {
  102. try {
  103. const response = await axios.get(`http://localhost/dev-api${apiPath}`, {
  104. headers: {
  105. Authorization: `Bearer ${token}`,
  106. clientid: CONFIG.clientId,
  107. referer: CONFIG.referer,
  108. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
  109. },
  110. timeout: 10000,
  111. });
  112. return response.data;
  113. } catch (error) {
  114. console.error('API调用失败:', error.response?.data?.msg || error.message);
  115. return null;
  116. }
  117. }
  118. // 导出函数
  119. module.exports = {
  120. getToken,
  121. callAPIWithToken,
  122. CONFIG,
  123. CREDENTIALS,
  124. };
  125. // 直接运行
  126. if (require.main === module) {
  127. console.log('🚀 快速Token获取器');
  128. console.log('='.repeat(40));
  129. getToken().then(async (token) => {
  130. if (token) {
  131. console.log('\n💡 使用示例:');
  132. console.log(`const token = "${token.substring(0, 50)}...";`);
  133. console.log('// 使用这个Token调用其他API');
  134. // 示例:获取用户信息
  135. console.log('\n🧪 测试API调用...');
  136. const userInfo = await callAPIWithToken(token, '/system/user/getInfo');
  137. if (userInfo && userInfo.code === 200) {
  138. console.log('✅ API调用成功! 用户:', userInfo.data.user.nickName);
  139. }
  140. console.log('\n='.repeat(40));
  141. console.log('🎯 Token已保存到变量中,可以直接使用!');
  142. }
  143. });
  144. }