com.aliyuncs.sts.model.v20150401.AssumeRoleResponse Java Examples

The following examples show how to use com.aliyuncs.sts.model.v20150401.AssumeRoleResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OSSUtil.java    From xnx3 with Apache License 2.0 6 votes vote down vote up
static AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret,String roleArn, String roleSessionName, String policy,ProtocolType protocolType) throws ClientException {
	try {
		// 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
		IClientProfile profile = DefaultProfile.getProfile(region_cn_hangzhou, accessKeyId, accessKeySecret);
		DefaultAcsClient client = new DefaultAcsClient(profile);
		// 创建一个 AssumeRoleRequest 并设置请求参数
		final AssumeRoleRequest request = new AssumeRoleRequest();
		request.setVersion(sta_api_version);
		request.setMethod(MethodType.POST);
		request.setProtocol(protocolType);
		request.setRoleArn(roleArn);
		request.setRoleSessionName(roleSessionName);
		request.setPolicy(policy);
		// 发起请求,并得到response
		final AssumeRoleResponse response = client.getAcsResponse(request);
		return response;
	} catch (ClientException e) {
		throw e;
	}
}
 
Example #2
Source File: STSServiceImpl.java    From jframe with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> getTempAccessPerm(String id) {
    ProtocolType protocolType = ProtocolType.HTTPS;
    try {
        final AssumeRoleResponse response = assumeRole(id, _config.getConf(id, K_roleArn), _config.getConf(id, K_roleSessionName),
                _config.getConf(id, K_policy), protocolType);

        Map<String, String> rsp = new HashMap<String, String>(3, 1);
        rsp.put(K_accessKeyId, response.getCredentials().getAccessKeyId());
        rsp.put(K_accessKeySecret, response.getCredentials().getAccessKeySecret());
        rsp.put(K_securityToken, response.getCredentials().getSecurityToken());
        return rsp;
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }

    return Collections.emptyMap();
}
 
Example #3
Source File: STSServiceImpl.java    From jframe with Apache License 2.0 6 votes vote down vote up
AssumeRoleResponse assumeRole(String id, String roleArn, String roleSessionName, String policy, ProtocolType protocolType)
        throws ServerException, com.aliyuncs.exceptions.ClientException {
    DefaultAcsClient client = clients.get(id);

    // 创建一个 AssumeRoleRequest 并设置请求参数
    final AssumeRoleRequest request = new AssumeRoleRequest();
    request.setVersion(_config.getConf(id, K_api_version));
    request.setMethod(MethodType.POST);
    request.setProtocol(protocolType);

    request.setRoleArn(roleArn);
    request.setRoleSessionName(roleSessionName);
    request.setPolicy(policy);

    request.setDurationSeconds(Long.parseLong(_config.getConf(id, K_durationSeconds, "3600"))); // 默认值为3600

    // 发起请求,并得到response
    final AssumeRoleResponse response = client.getAcsResponse(request);
    // client.shutdown();

    return response;
}
 
Example #4
Source File: StsServiceSample.java    From jframe with Apache License 2.0 6 votes vote down vote up
static AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret, String roleArn, String roleSessionName, String policy,
                                     ProtocolType protocolType) throws ClientException {
    try {
        // 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
        IClientProfile profile = DefaultProfile.getProfile(REGION_CN_HANGZHOU, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);

        // 创建一个 AssumeRoleRequest 并设置请求参数
        final AssumeRoleRequest request = new AssumeRoleRequest();
        request.setVersion(STS_API_VERSION);
        request.setMethod(MethodType.POST);
        request.setProtocol(protocolType);

        request.setRoleArn(roleArn);
        request.setRoleSessionName(roleSessionName);
        request.setPolicy(policy);

        // 发起请求,并得到response
        final AssumeRoleResponse response = client.getAcsResponse(request);

        return response;
    } catch (ClientException e) {
        throw e;
    }
}
 
Example #5
Source File: AbstractClientProvider.java    From alibaba-flink-connectors with Apache License 2.0 5 votes vote down vote up
@Override
public InnerStsIdentity load(String key) throws Exception {
	logger.info("getAssumeRole with para accessId " + stsAccessId + ", secretKey " +
			stsAccessKey + ", roleArn " + stsRoleArn +
			", stsSessionName " + stsSessionName);
	AssumeRoleResponse role = StsServiceRequest.assumeRoleWithServiceIdentity(
			stsAccessId, stsAccessKey, stsRoleArn, stsSessionName, stsAssumeRoleFor, properties);
		return new InnerStsIdentity(role.getCredentials().getAccessKeyId(),
				role.getCredentials().getAccessKeySecret(),
				role.getCredentials().getSecurityToken());
}
 
Example #6
Source File: FunctionComputeClientTest.java    From fc-java-sdk with MIT License 5 votes vote down vote up
private Credentials getAssumeRoleCredentials(String policy)
    throws com.aliyuncs.exceptions.ClientException {
    IClientProfile profile = DefaultProfile
        .getProfile(REGION, ACCESS_KEY, SECRET_KEY);
    //DefaultProfile.addEndpoint("sts.us-west-1.aliyuncs.com", "us-west-1", "Sts", "sts.us-west-1.aliyuncs.com");
    DefaultAcsClient client = new DefaultAcsClient(profile);

    AssumeRoleRequest request = new AssumeRoleRequest();
    request.setVersion(STS_API_VERSION);
    request.setMethod(MethodType.POST);
    request.setProtocol(ProtocolType.HTTPS);
    request.setRoleArn(STS_ROLE);
    request.setRoleSessionName("test-session");
    if (policy != null) {
        request.setPolicy(policy);
    }

    AssumeRoleResponse stsResponse;
    try {
        stsResponse = client.getAcsResponse(request);
    } catch (com.aliyuncs.exceptions.ClientException e) {
        throw new RuntimeException(e);
    }

    String accessKey = stsResponse.getCredentials().getAccessKeyId();
    String secretKey = stsResponse.getCredentials().getAccessKeySecret();
    String stsToken = stsResponse.getCredentials().getSecurityToken();

    assertNotNull(accessKey);
    assertNotNull(secretKey);
    assertNotNull(stsToken);

    return stsResponse.getCredentials();
}
 
Example #7
Source File: StsServiceRequest.java    From alibaba-flink-connectors with Apache License 2.0 4 votes vote down vote up
public static AssumeRoleResponse assumeRoleWithServiceIdentity(
			final String streamAccessId, final String streamAccessKey,
			final String roleArn, final String roleSessionName,
			final String assumeRoleFor,
			Configuration properties) throws Exception {
		//decode
		String decodeKey = DecodeUtil.decrypt(streamAccessKey, StsConstants.STS_SECRET_KEY);

		String regionId = properties.getString(BlinkOptions.STS.STS_REGION_ID);

		// 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
		IClientProfile profile = DefaultProfile.getProfile(
				regionId, streamAccessId, decodeKey);
		DefaultAcsClient client = new DefaultAcsClient(profile);

		// endPoints format:   endPointName#regionId#product#domain,endPointName1#regionId1#product1#domain1
		if (properties.containsKey(INNER_STS_ENDPOINT) && properties.getString(INNER_STS_ENDPOINT, null) != null){
			String endPoints = properties.toMap().get(INNER_STS_ENDPOINT);
			if (!endPoints.isEmpty()) {
				String[] endPointItem = endPoints.split(",");
				for (String item : endPointItem) {
					String[] partItems = item.split("#");
					if (null != partItems && partItems.length == 4) {
						DefaultProfile.addEndpoint(partItems[0], partItems[1], partItems[2], partItems[3]);
					}
				}
			}
		}

		// 创建一个 AssumeRoleRequest 并设置请求参数
		final AssumeRoleRequest request = new AssumeRoleRequest();
		request.setMethod(MethodType.POST);

		request.setProtocol(PROTOCOL_TYPE);
		request.setDurationSeconds(DURATION);
		request.setRoleArn(roleArn);
		request.setRoleSessionName(roleSessionName);
//		request.setAssumeRoleFor(assumeRoleFor);
		X509TrustAll.ignoreSSLCertificate();
		// 发起请求,并得到response
		final AssumeRoleResponse response = client.getAcsResponse(request);

		return response;
	}
 
Example #8
Source File: OSSUtil.java    From xnx3 with Apache License 2.0 4 votes vote down vote up
/**
	 * STS 授权给第三方上传,获得临时访问凭证
	 * @param roleSessionName 临时Token的会话名称,自己指定用于标识你的用户,主要用于审计,或者用于区分Token颁发给谁
	 * 							<br/>注意RoleSessionName的长度和规则,不要有空格,只能有'-' '_' 字母和数字等字符
	 * 							<br/>具体规则请参考API文档中的格式要求
	 * 							<br/>如:alice-001
	 * @param policy RAM和STS授权策略,详细参考 <a href="https://help.aliyun.com/document_detail/31867.html">https://help.aliyun.com/document_detail/31867.html</a>
	 * 			<pre>
	 * 				{
	 * 					"Version": "1",
	 * 					"Statement": [
	 * 						{
	 * 							"Action": [
	 * 								"oss:PutObject", 
	 * 								"oss:GetObject"
	 * 							], 
	 * 							"Resource": [
	 * 								"acs:oss:*:*:*"
	 * 							], 
	 * 							"Effect": "Allow",
	 * 							"Condition": {
	 * 								"IpAddress": {
	 * 									"acs:SourceIp": "192.168.0.*"	//指定ip网段,支持*通配
	 * 								}
	 * 							}
	 * 						}
	 * 					]
	 * 				}
	 * 			</pre>
	 * @return 成功,返回 {@link Credentials} ,失败返回null
	 */
	public static Credentials createSTS(String roleSessionName,String policy){
		String accessKeyId = OSSUtil.accessKeyId;
	    String accessKeySecret = OSSUtil.accessKeySecret;
	    // AssumeRole API 请求参数: RoleArn, RoleSessionName, Policy, and DurationSeconds
	    // RoleArn 需要在 RAM 控制台上获取
//	    String roleArn = "acs:ram::1080155601964967:role/aliyunosstokengeneratorrole";
	    // RoleSessionName 是临时Token的会话名称,自己指定用于标识你的用户,主要用于审计,或者用于区分Token颁发给谁
	    // 但是注意RoleSessionName的长度和规则,不要有空格,只能有'-' '_' 字母和数字等字符
	    // 具体规则请参考API文档中的格式要求
//		String roleSessionName = "alice-001";
	    // 如何定制你的policy?
//		    String policy = "{\n" +
//		            "    \"Version\": \"1\", \n" +
//		            "    \"Statement\": [\n" +
//		            "        {\n" +
//		            "            \"Action\": [\n" +
//		            "                \"oss:GetBucket\", \n" +
//		            "                \"oss:GetObject\" \n" +
//		            "            ], \n" +
//		            "            \"Resource\": [\n" +
//		            "                \"acs:oss:*:*:*\"\n" +
//		            "            ], \n" +
//		            "            \"Effect\": \"Allow\"\n" +
//		            "        }\n" +
//		            "    ]\n" +
//		            "}";
	    // 此处必须为 HTTPS
	    ProtocolType protocolType = ProtocolType.HTTPS;
	    try {
	    	AssumeRoleResponse response = assumeRole(accessKeyId, accessKeySecret,roleArn, roleSessionName, policy, protocolType);
	    	Credentials credentials = response.getCredentials();
	    	return credentials;
	    } catch (ClientException e) {
	    	e.printStackTrace();
	    	System.out.println("Failed to get a token.");
	    	System.out.println("Error code: " + e.getErrCode());
	    	System.out.println("Error message: " + e.getErrMsg());
	    }
	    return null;
	}
 
Example #9
Source File: StsServiceSample.java    From jframe with Apache License 2.0 4 votes vote down vote up
@Test
public void tokenTest() {
    // 只有 RAM用户(子账号)才能调用 AssumeRole 接口
    // 阿里云主账号的AccessKeys不能用于发起AssumeRole请求
    // 请首先在RAM控制台创建一个RAM用户,并为这个用户创建AccessKeys
    String accessKeyId = "";
    String accessKeySecret = "";

    // AssumeRole API 请求参数: RoleArn, RoleSessionName, Polciy, and
    // DurationSeconds

    // RoleArn 需要在 RAM 控制台上获取
    String roleArn = "";

    // RoleSessionName 是临时Token的会话名称,自己指定用于标识你的用户,主要用于审计,或者用于区分Token颁发给谁
    // 但是注意RoleSessionName的长度和规则,不要有空格,只能有'-' '_' 字母和数字等字符
    // 具体规则请参考API文档中的格式要求
    String roleSessionName = "oss-app-client";

    // 如何定制你的policy?
    // String policy = "{\"Statement\": [{\"Action\": \"oss:*\", "
    // + "\"Effect\": \"Allow\",\"Resource\": \"*\"}],\"Version\": \"1\"}";
    String policy = "{" + " \"Statement\": [ " + "             { " + "                \"Action\": \"oss:*\", "
            + "                 \"Effect\": \"Allow\", " + "                \"Resource\": \"*\" " + "            } " + "          ], "
            + "        \"Version\": \"1\" " + "     } ";

    // String policy = "{\"Statement\": [{\"Action\": \"sts:AssumeRole\","
    // + "\"Effect\": \"Allow\",\"Principal\":{\"Service\":
    // [\"oas.aliyuncs.com\"]}}],\"Version\": \"1\"}";
    // 此处必须为 HTTPS
    ProtocolType protocolType = ProtocolType.HTTPS;

    try {
        final AssumeRoleResponse response = assumeRole(accessKeyId, accessKeySecret, roleArn, roleSessionName, policy, protocolType);

        System.out.println("Expiration: " + response.getCredentials().getExpiration());
        System.out.println("Access Key Id: " + response.getCredentials().getAccessKeyId());
        System.out.println("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
        System.out.println("Security Token: " + response.getCredentials().getSecurityToken());
    } catch (

            ClientException e) {
        System.out.println("Failed to get a token.");
        System.out.println("Error code: " + e.getErrCode());
        System.out.println("Error message: " + e.getErrMsg());
    }

}