| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- import com.aliyun.sts20150401.models.AssumeRoleResponse;
- import com.aliyun.sts20150401.models.AssumeRoleResponseBody;
- import com.aliyun.tea.TeaException;
- /**
- * @author reghao
- * @date 2024-08-30 13:48:52
- */
- public class AliyunTest {
- /**
- * <b>description</b> :
- * <p>使用AK&SK初始化账号Client</p>
- * @return Client
- *
- * @throws Exception
- */
- public static com.aliyun.sts20150401.Client createClient() throws Exception {
- // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
- // 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378657.html。
- com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
- // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
- .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
- // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
- .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
- // Endpoint 请参考 https://api.aliyun.com/product/Sts
- config.endpoint = "sts.cn-chengdu.aliyuncs.com";
- return new com.aliyun.sts20150401.Client(config);
- }
- public static void test(String... args0) throws Exception {
- java.util.List<String> args = java.util.Arrays.asList(args0);
- com.aliyun.sts20150401.Client client = createClient();
- com.aliyun.sts20150401.models.AssumeRoleRequest assumeRoleRequest = new com.aliyun.sts20150401.models.AssumeRoleRequest();
- String roleArn = "acs:ram::1727220085568559:role/hao-sts";
- assumeRoleRequest.setRoleArn(roleArn);
- assumeRoleRequest.setRoleSessionName("role_session_test");
- com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
- try {
- // 复制代码运行请自行打印 API 的返回值
- AssumeRoleResponse roleResponse = client.assumeRoleWithOptions(assumeRoleRequest, runtime);
- AssumeRoleResponseBody.AssumeRoleResponseBodyCredentials credentials = roleResponse.getBody().getCredentials();
- String id = credentials.getAccessKeyId();
- String secret = credentials.getAccessKeySecret();
- String expiration = credentials.getExpiration();
- String token = credentials.getSecurityToken();
- System.out.println();
- } catch (TeaException error) {
- // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
- // 错误 message
- System.out.println(error.getMessage());
- // 诊断地址
- System.out.println(error.getData().get("Recommend"));
- com.aliyun.teautil.Common.assertAsString(error.message);
- } catch (Exception _error) {
- TeaException error = new TeaException(_error.getMessage(), _error);
- // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
- // 错误 message
- System.out.println(error.getMessage());
- // 诊断地址
- System.out.println(error.getData().get("Recommend"));
- com.aliyun.teautil.Common.assertAsString(error.message);
- }
- }
- }
|