# huaweicloud-iam-securitytokens-java **Repository Path**: HuaweiCloudDeveloper/huaweicloud-iam-securitytokens-java ## Basic Information - **Project Name**: huaweicloud-iam-securitytokens-java - **Description**: 通过token获取临时访问密钥和securitytoken/通过委托获取临时访问密钥和securitytoken - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master-dev - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2023-07-10 - **Last Updated**: 2025-06-16 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ## 1.功能介绍 该场景可以用于通过token获取临时访问密钥;通过委托获取临时访问密钥。 临时AK/SK和securitytoken是系统颁发给IAM用户的临时访问令牌,有效期可在15分钟至24小时范围内设置, 过期后需要重新获取。 临时AK/SK和securitytoken遵循权限最小化原则。鉴权时,临时AK/SK和securitytoken必须同时使用,请求头中需要添加“x-security-token”字段, 使用方法详情请参考:[使用临时AK/SK做签名](https://support.huaweicloud.com/devg-apisign/api-sign-securetoken.html)。 ## 2.前提条件 2.1获取AK/SK与其他参数 开发者在使用前需先获取账号的ak、sk、domainId、domainName、agencyName等字段(每个字段在demo中有详细文字描述,参见代码)。 * domainId:委托方A的账号ID。 * domainName:委托方A的账号名称。 * agencyName:委托方A创建的委托的名称。 * version:固定值,1.0表系统预置的角色。1.1表示创建自定义策略。 * effect:固定值,填Allow或者Deny。 您需要拥有华为云账号以及该账号对应的 Access Key(AK)和 Secret Access Key(SK)。 请在华为云控制台“我的凭证-访问密钥”页面上创建和查看您的 AK/SK,更多信息请查看[访问密钥](https://support.huaweicloud.com/usermanual-ca/zh-cn_topic_0046606340.html)。 2.2SDK的获取和安装 您可以通过如下方式获取和安装 SDK:通过 Maven 安装项目依赖是使用 Java SDK 的推荐方法, 首先您需要在您的操作系统中下载并安装 Maven ,安装完成后您只需在 Java 项目的 pom.xml 文件加入相应的依赖项即可。本示例使用IAM SDK: com.huaweicloud.sdk huaweicloud-sdk-iam 3.1.28 2.3通用准备 2.3.1导入依赖模块部分示例 import com.huaweicloud.sdk.core.auth.GlobalCredentials; import com.huaweicloud.sdk.core.exception.ClientRequestException; import com.huaweicloud.sdk.core.http.HttpConfig; import com.huaweicloud.sdk.core.utils.StringUtils; 2.3.2配置客户端属性 HttpConfig config = HttpConfig.getDefaultHttpConfig(); config.withIgnoreSSLVerification(true); // 如果是本地IDEA调试,需要使用代理,代码如下: // config.setProxyHost(""); // config.setProxyPort(); // config.setProxyUsername(""); // config.setProxyPassword(""); 2.3.3创建认证 GlobalCredentials auth = new GlobalCredentials() .withAk(ak) .withSk(sk) .withDomainId(domainId); 2.3.4创建请求客户端 ArrayList endpoints = new ArrayList(); endpoints.add("https://iam.myhuaweicloud.com"); IamClient client = IamClient.newBuilder() .withCredential(auth) .withEndpoints(endpoints) .withHttpConfig(config).build(); ## 3.运行环境 Java JDK 1.8 及其以上版本。 ## 4.关键代码 public class Application { private static final Logger logger = LoggerFactory.getLogger(Application.class); public static void main(String[] args) { // 认证用的ak和sk硬编码到代码中或者明文存储都有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全; // 本示例以ak和sk保存在环境变量中来实现身份验证为例,运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK。 String ak = System.getenv("HUAWEICLOUD_SDK_AK"); String sk = System.getenv("HUAWEICLOUD_SDK_SK"); String domainId = ""; // 租户id:domainId,必传 // 配置客户端属性 HttpConfig config = HttpConfig.getDefaultHttpConfig(); config.withIgnoreSSLVerification(true); // 创建认证 GlobalCredentials auth = new GlobalCredentials() .withAk(ak) .withSk(sk) .withDomainId(domainId); // 创建请求客户端 ArrayList endpoints = new ArrayList(); endpoints.add(""); // 固定值,填入:https://iam.myhuaweicloud.com IamClient client = IamClient.newBuilder() .withCredential(auth) .withEndpoints(endpoints) .build(); // 通过token获取临时访问密钥 createTemporaryAccessKeyByToken(client); // 通过委托获取临时访问密钥 createTemporaryAccessKeyByAgency(client); } private static void createTemporaryAccessKeyByToken(IamClient client) { int durationSeconds = 0; // AK、SK和securitytoken的有效期,时间单位为秒。取值范围:[900,86400] ,默认为15min。选填 String version = ""; // 权限版本号。1.0:系统预置的角色。1.1创建自定义策略。必填 // 授权项,指对资源的具体操作权限。格式为:服务名:资源类型:操作,例:vpc:ports:create。支持通配符号*,无需罗列全部授权项。必填 ArrayList actions = new ArrayList(); // actions里面需要添加授权项目,如下示例 // actions.add("vpc:ports:create"); String effect = ""; // 固定值,填Allow或者Deny。必填 // 构造请求 CreateTemporaryAccessKeyByTokenRequest request = new CreateTemporaryAccessKeyByTokenRequest(); CreateTemporaryAccessKeyByTokenRequestBody body = new CreateTemporaryAccessKeyByTokenRequestBody(); // 获取listPolicyStatement List listPolicyStatement = getListPolicyStatement(actions, effect); ServicePolicy policyIdentity = new ServicePolicy(); policyIdentity.withVersion(version) .withStatement(listPolicyStatement); IdentityToken tokenIdentity = new IdentityToken(); if (durationSeconds >= 900 && durationSeconds <= 86400) { tokenIdentity.withDurationSeconds(durationSeconds); } List listIdentityMethods = new ArrayList(); listIdentityMethods.add(TokenAuthIdentity.MethodsEnum.fromValue("token")); TokenAuthIdentity identityAuth = new TokenAuthIdentity(); identityAuth.withMethods(listIdentityMethods) .withToken(tokenIdentity) .withPolicy(policyIdentity); TokenAuth authbody = new TokenAuth(); authbody.withIdentity(identityAuth); body.withAuth(authbody); request.withBody(body); try { // 执行请求 CreateTemporaryAccessKeyByTokenResponse response = client.createTemporaryAccessKeyByToken(request); logger.info(response.toString()); } catch (ClientRequestException e) { LogError(e); } } private static void createTemporaryAccessKeyByAgency(IamClient client) { String version = "1.1"; // 权限版本号。1.0:系统预置的角色。1.1创建自定义策略。必填 // 授权项,指对资源的具体操作权限。格式为:服务名:资源类型:操作,例:vpc:ports:create。支持通配符号*,无需罗列全部授权项。必填 ArrayList actions = new ArrayList(); // actions里面需要添加授权项目,如下示例 // actions.add("vpc:ports:create"); String effect = ""; // 固定值,填Allow或者Deny。必填 String agencyName = ""; // 委托名。必填 // domainId和domainName二选一 String domainId = ""; // 委托方的账号ID。二选一 String domainName = ""; // 委托方的账号名。二选一 // 委托方对应的企业用户名长度5~64,只能包含大写字母、小写字母、数字(0-9)、特殊字符("-"与"_")且只能以字母开头。选填 String sessionUserName = ""; int durationSeconds = 0; // AK、SK和securitytoken的有效期,时间单位为秒。取值范围:[900,86400] ,默认为15min。选填 // 构造请求 CreateTemporaryAccessKeyByAgencyRequest request = new CreateTemporaryAccessKeyByAgencyRequest(); CreateTemporaryAccessKeyByAgencyRequestBody body = new CreateTemporaryAccessKeyByAgencyRequestBody(); // 获取listPolicyStatement List listPolicyStatement = getListPolicyStatement(actions, effect); ServicePolicy policyIdentity = new ServicePolicy(); policyIdentity.withVersion(version) .withStatement(listPolicyStatement); IdentityAssumerole assumeRoleIdentity = new IdentityAssumerole(); assumeRoleIdentity.withAgencyName(agencyName); if (!StringUtils.isEmpty(domainId)) { assumeRoleIdentity.withDomainId(domainId); } else if (!StringUtils.isEmpty(domainName)) { assumeRoleIdentity.withDomainName(domainName); } if (durationSeconds >= 900 && durationSeconds <= 86400) { assumeRoleIdentity.withDurationSeconds(durationSeconds); } if (!StringUtils.isEmpty(sessionUserName)) { AssumeroleSessionuser sessionUserAssumeRole = new AssumeroleSessionuser(); sessionUserAssumeRole.withName(sessionUserName); assumeRoleIdentity.withSessionUser(sessionUserAssumeRole); } List listIdentityMethods = new ArrayList(); listIdentityMethods.add(AgencyAuthIdentity.MethodsEnum.fromValue("assume_role")); AgencyAuthIdentity identityAuth = new AgencyAuthIdentity(); identityAuth.withMethods(listIdentityMethods) .withAssumeRole(assumeRoleIdentity) .withPolicy(policyIdentity); AgencyAuth authbody = new AgencyAuth(); authbody.withIdentity(identityAuth); body.withAuth(authbody); request.withBody(body); try { // 执行请求 CreateTemporaryAccessKeyByAgencyResponse response = client.createTemporaryAccessKeyByAgency(request); logger.info(response.toString()); } catch (ClientRequestException e) { LogError(e); } } private static List getListPolicyStatement(ArrayList actions, String effect) { List listStatementAction = new ArrayList(); for (String action : actions) { listStatementAction.add(action); } List listPolicyStatement = new ArrayList(); listPolicyStatement.add( new ServiceStatement() .withAction(listStatementAction) .withEffect(ServiceStatement.EffectEnum.fromValue(effect)) ); return listPolicyStatement; } private static void LogError(ClientRequestException e) { logger.error("HttpStatusCode: " + e.getHttpStatusCode()); logger.error("RequestId: " + e.getRequestId()); logger.error("ErrorCode: " + e.getErrorCode()); logger.error("ErrorMsg: " + e.getErrorMsg()); } } ## 5.如何运行 该场景可以用于通过token获取临时访问密钥;通过委托获取临时访问密钥。 各个方法可以独立执行,替换参数后,可以根据需要执行的方法注释掉其他方法,执行Run启动main方法即可。 ## 6.返回结果示例 6.1返回结果示例:通过token获取临时访问密钥 { credential: class Credential { expiresAt: 2023-07-25T08:50:05.445000Z access: IAH4**********9N4V secret: 7mMG********************XCC1 securitytoken: ggpjbi1ub3J0a…… } } 6.2返回结果示例:通过委托获取临时访问密钥 { credential: class Credential { expiresAt: 2023-07-25T08:50:05.445000Z access: 5RTW***************DI70 secret: 41Xt*************************3C securitytoken: ggpjbi1ub3J0aC0... } } ## 7.其他语言版本的说明 本代码参考华为云API Explorer的代码示例开发Java语言版本,对接SDK,如需使用其他版本,亦可参考华为云API Explorer提供的其他语言代码示例,链接如下: * [通过token获取临时访问密钥](https://console.huaweicloud.com/apiexplorer/#/openapi/IAM/sdk?api=CreateTemporaryAccessKeyByToken) * [通过委托获取临时访问密钥](https://console.huaweicloud.com/apiexplorer/#/openapi/IAM/sdk?api=CreateTemporaryAccessKeyByAgency) ## 8.修订记录 | 发布日期 | 文档版本 | 修订说明 | |---------| ------------ | ------------ | | 2023-08 | 1.0 | 文档首次发布 |