- 安装依赖
yarn add axiosyarn add urlencodeyarn add crypto-jsyarn add qs复制代码
- 导包
const axios = require('axios');const urlencode = require('urlencode');const CryptoJS = require('crypto-js');const crypto = require('crypto');const qs = require('qs');复制代码
- 代码实现
async function aliyunSTS2() { var params = { AccessKeyId: '阿里云AccessKeyId', Action: 'AssumeRole', Format: 'JSON', RoleArn: 'acs:ram::xxxxxxxx:role/xxxxxx', RoleSessionName: 'ann-sts-nodejs 此处自定义,注意字符限制 字母和-数字的组合', SignatureMethod: 'HMAC-SHA1', SignatureNonce: new Date().getTime().toLocaleString(),//随机字符串吧 SignatureVersion: '1.0', Timestamp: new Date().toISOString().replace(/\..+/,'') + 'Z', Version: '2015-04-01' } var CanonicalizedQueryString = qs.stringify(params) console.log('CanonicalizedQueryString') console.log(CanonicalizedQueryString) var StringToSign = 'GET' +'&' + urlencode('/') + '&' + urlencode(CanonicalizedQueryString) // StringToSign = urlencode(StringToSign) console.log('StringToSign') console.log(StringToSign) const key = '阿里云AccessKey Secret'; var sign = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(StringToSign,`${key}&`)) console.log('签名') console.log(sign) // var signCode = new Buffer(sign).toString('base64'); console.log('签名Base64') // console.log(signCode) const hmac = crypto.createHmac('sha1', `${key}&`); const signature = hmac.update(StringToSign) .digest("base64"); console.log('const signature = ') console.log(signature) axios.default.get('https://sts.aliyuncs.com', { params: { ...params, Signature: signature ,//sign也可以 两种加密库的实现,浏览器环境和node环境的切换吧,自己选 } } ).then((res)=>{ console.log('axios then') console.log(res.data) console.log(res.data.Credentials.SecurityToken) }).catch((err)=>{ console.log('axios 请求错误') console.log(err.response.data)//阿里云解析错误会返回信息的 })}复制代码
- 验证
aliyunSTS2()复制代码
第三方实现,只支持node环境
- 安装依赖
yarn add blueshit/aliyun-sts复制代码
const STS = require("@blueshit/aliyun-sts");async function getSts() { const sts = new STS.STS({ accessKeyId: "阿里云accessKeyId", accessKeySecret: "阿里云accessKeySecret", }); const policy = { Statement: [ { Effect: "Allow", Action: ["oss:*"], Resource: ['acs:oss:*:*:*'], }, ], Version: "1", }; const credentials = await sts.assumeRole('acs:ram::xxxx:role/此处阿里云自己的角色ID', policy, 15 * 60, "RoleSessionName"); console.log(credentials);}复制代码
- 验证
getSts()复制代码