前端获取后端数据:
getOssToken () {
this.$http({
url: this.$http.adornUrl('/ossUser/temp'),
method: 'get'
}).then(({data}) => {
if (data && data.code === 200) {
this.ossConfig.accessKeyId = data.body.accessKeyId
this.ossConfig.accessKeySecret = data.body.accessKeySecret
this.ossConfig.stsToken = data.body.securityToken
console.log('返回的数据为')
console.log(data)
} else {
this.$message.error('服务端账号失效')
}
})
ossConfig: {
region: 'oss-cn-shanghai',
accessKeyId: null,
accessKeySecret: null,
stsToken: null,
bucket: 'coach-1'
},
结果:
{msg: '操作成功', code: 200, body: {…}} 下面为打开:
body: {accessKeyId: xxxx', accessKeySecret: 'xxxxx7sBt7xZJKEx9mXHmoQ7UwdZs5', securityToken: 'xxxxxxTQbONhoha…MDbAeRsp8Q9w3TwFhgvksEzOyBNwwRmnmy/j6/RD9onDsrPM='}
code: 200
msg: "操作成功"
[[Prototype]]: Object
后端获取token
@GetMapping("/temp")
@ApiOperation("临时用户")
public BaseR<?> getTempUser() {
String roleSessionName = "manageSession";
String key = RedisKeys.getOssConfigKey(roleSessionName);
OssUserVo ossUserVo = redisUtils.get(key, OssUserVo.class);
if (! Objects.equals(ossUserVo,null)) {
return BaseR.ok(ossUserVo);
}
String endpoint = "sts.cn-shanghai.aliyuncs.com";
String AccessKeyId = projectConfig.getAccessKeyId();
String accessKeySecret = projectConfig.getAccessKeySecret();
String roleArn = projectConfig.getArn();
String policy = "{\n" +
" \"Version\": \"1\", \n" +
" \"Statement\": [\n" +
" {\n" +
" \"Action\": [\n" +
" \"oss:PutObject\"\n" +
" ], \n" +
" \"Resource\": [\n" +
" \"acs:oss:*:*:coach-1/*\" \n" +
" ], \n" +
" \"Effect\": \"Allow\"\n" +
" }\n" +
" ]\n" +
"}";
OssUserVo ossUser = new OssUserVo();
try {
DefaultProfile.addEndpoint("", "", "Sts", endpoint);
IClientProfile profile = DefaultProfile.getProfile("", AccessKeyId, accessKeySecret);
DefaultAcsClient client = new DefaultAcsClient(profile);
final AssumeRoleRequest request = new AssumeRoleRequest();
request.setMethod(MethodType.POST);
request.setRoleArn(roleArn);
request.setRoleSessionName(roleSessionName);
request.setPolicy(policy);
request.setDurationSeconds(3600L);
final AssumeRoleResponse response = client.getAcsResponse(request);
ossUser.setAccessKeyId(response.getCredentials().getAccessKeyId())
.setAccessKeySecret(response.getCredentials().getAccessKeySecret())
.setSecurityToken(response.getCredentials().getSecurityToken());
}catch (ClientException e) {
log.error("获取oss临时秘钥失败:{}",e);
return BaseR.error("获取oss临时秘钥失败: "+e.getMessage());
}
redisUtils.set(key,ossUser,3600);
return BaseR.ok(ossUser);
}