Access DataHub using STS

更新时间:
复制 MD 格式

Security Token Service (STS) lets you manage temporary access from other users to your Alibaba Cloud resources. You can use STS to create temporary access tokens for Resource Access Management (RAM) entities such as RAM users and RAM roles. You can also specify a custom validity period and configure the access permissions of the STS tokens. STS token holders can have temporary access to DataHub by writing code or calling API operations.

Example

  1. Add dependencies using Maven.

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-sts</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.4.6</version>
</dependency>
<dependency>
    <groupId>com.aliyun.datahub</groupId>
    <artifactId>aliyun-sdk-datahub</artifactId>
    <version>2.19.0-public</version>
</dependency>
  1. Example:

  • Description:

Name

Type

Required

Example

Description

RoleArn

String

Yes

acs:ram::123456789012****:role/adminrole

The Alibaba Cloud Resource Name (ARN) of the RAM role. Format: acs:ram::$accountID:role/$roleName.

RoleSessionName

String

Yes

alice

A user-defined parameter that is used for distinguishing different tokens and for user-level access auditing.

The value must be 2 to 32 characters in length. It can contain letters, numbers, periods (.), at signs (@), hyphens (-), and underscores (_).

Policy

String

No

{"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}

Access policy.

You can use this parameter to grant the STS token fewer permissions than the permissions granted to the RAM role. If you do not specify this parameter, the returned STS token has all the permissions of the RAM role.

The value must be 1 to 1,024 characters in length.

DurationSeconds

Long

No

3600

The time-to-live (TTL) in seconds.

Minimum value: 900. Maximum value: the value of the MaxSessionDuration parameter. Default value: 3600.

Note

  • $accountID: Your Alibaba Cloud account ID. You can find it by logging in to the Alibaba Cloud Management Console, hovering over the profile picture in the upper-right corner, and clicking Security Settings.

  • $roleName: specifies the name of the RAM role. To view the name of the RAM role, log on to the RAM console, click Roles in the navigation pane on the left, and then view the name of the RAM role in the Role Name column on the page that appears.

  • MaxSessionDuration: specifies the maximum session time of the RAM role. You can call the CreateRole or UpdateRole operation to set this parameter. For more information, see CreateRole or UpdateRole.

  • You must also configure the AccessKey ID and AccessKey secret in your project.

    datahub.endpoint=<yourEndpoint>
    datahub.accessId=<yourAccessKeyId>
    datahub.accessKey=<yourAccessKeySecret>
    Important

    The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using the AccessKey pair to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.

    Do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey leak and compromise the security of all resources in your account.

import com.aliyun.datahub.client.DatahubClient;
import com.aliyun.datahub.client.DatahubClientBuilder;
import com.aliyun.datahub.client.auth.AliyunAccount;
import com.aliyun.datahub.client.common.DatahubConfig;
import com.aliyun.datahub.client.http.HttpConfig;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;

public class AssumeRole {

    // The China (Hangzhou) region is used as an example.
    private static final String regionId = "cn-hangzhou";
    // The AccessKey pair of the RAM user.
		@Value("${datahub.accessId}")
		String accessId;
		@Value("${datahub.accessKey}")
		String accessKey;
    // In this example, the account ID is 198800131028**** and the role name is admin.
    private static final String roleArn = "acs:ram::198800131028****:role/admin";
    // sessionName: A custom parameter used to distinguish between different tokens.
    private static final String sessionName = "alice";
    // The endpoint of the China (Hangzhou) region is used as an example.
    private static final String endpoint = "http://dh-cn-hangzhou.aliyuncs.com";

    public static void main(String[] args) {
        AssumeRoleResponse.Credentials token = AssumeRole.getToken();
        // Create a DatahubClient instance.
        DatahubClient datahubClient = DatahubClientBuilder.newBuilder()
                .setDatahubConfig(
                        new DatahubConfig(endpoint,
                                new AliyunAccount(token.getAccessKeyId(), token.getAccessKeySecret(), token.getSecurityToken()
                                ), true))
                .setHttpConfig(new HttpConfig().setCompressType(HttpConfig.CompressType.LZ4)
                        .setConnTimeout(10000))
                .build();

        // After the DatahubClient is initialized, you can access DataHub resources.
    }

    /**
     * Generate a temporary access token.
     */
    private static AssumeRoleResponse.Credentials getToken() {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessId, accessKey);
        IAcsClient client = new DefaultAcsClient(profile);
        // Construct the request and set the parameters. For more information about the parameters and how to set them, see STS API Reference.
        AssumeRoleRequest request = new AssumeRoleRequest();
        request.setRoleArn(roleArn);
        request.setRoleSessionName(sessionName);
        try {
            AssumeRoleResponse response = client.getAcsResponse(request);
            return response.getCredentials();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        return null;
    }
}