业务场景:
如果前端直接上传文件到OSS,势必要暴露令牌,无法精准控制上传内容等,使用临时令牌即可解决这个问题.
先去阿里云后台设置好token,角色,地区等
pom.xml
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
</dependency>
生成阿里云临时安全令牌(Security Token Service,STS)
@Service
public class OssServicesImpl implements OssServices {
@Value("${oss.AccessKeyId}")
private String AccessKeyId;
@Value("${oss.accessKeySecret}")
private String accessKeySecret;
@Value("${oss.roleArn}")
private String roleArn;
@Value("${oss.regionId}")
private String regionId;
/**
* 生成临时令牌,用来上传文件到oss
* @param roleSessionName 用户角色标识符号,格式:^[a-zA-Z0-9\.@\-_]+$ 2-50个字符
* @return 临时令牌
*/
@Override
public AssumeRoleResponse getSTS(String roleSessionName) {
DefaultProfile profile = DefaultProfile.getProfile(regionId, AccessKeyId, accessKeySecret);
IAcsClient client = new DefaultAcsClient(profile);
AssumeRoleRequest request = new AssumeRoleRequest();
request.setRoleArn(roleArn);
request.setRoleSessionName(roleSessionName);
request.setDurationSeconds(1000L); // 设置凭证有效时间
try {
return client.getAcsResponse(request);
} catch (ClientException e) {
System.out.println("Failed:");
System.out.println("Error code: " + e.getErrCode());
System.out.println("Error message: " + e.getErrMsg());
System.out.println("RequestId: " + e.getRequestId());
}
return null;
}
}