AWS-临时授权方式GetFederationToken

特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过。如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/mao2080/

1、问题描述

最近在做AWS-KVS方面的研究,需要给设备和APP颁布临时令牌。AWS操作说明给的例子不够详细重新网络上寻找资料解决。

2、POM文件

        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>sts</artifactId>
            <version>2.16.29</version>
        </dependency>
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>auth</artifactId>
            <version>2.16.29</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-kinesisvideo</artifactId>
            <version>1.11.700</version>
            <scope>compile</scope>
        </dependency>

3、核心代码

package com.demo.amazon.sts.service;

import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.Credentials;
import software.amazon.awssdk.services.sts.model.GetFederationTokenRequest;

public class GetFederationTokenTest {

    private final static String REGION_NAME = "ap-northeast-2";

    private final static String AK = "YOUR_ACCESS_KEY_ID";

    private final static String SK = "YOUR_SECRET_ACCESS_KEY";

    private final static String USER_NAME = "demo";

    public static void main(String[] args) throws Exception {

        String channelArn = "arn:aws:kinesisvideo:ap-northeast-2:YOUR_ACCOUNT_ID:channel/amzone-kvs-demo-test/1632657078926";

        String policy = "{\"Version\": \"2012-10-17\",\"Statement\": [{\"Sid\": \"VisualEditor0\",\"Effect\": \"Allow\",\"Action\": [\"kinesisvideo:GetSignalingChannelEndpoint\",\"kinesisvideo:ConnectAsMaster\",\"kinesisvideo:ConnectAsViewer\",\"kinesisvideo:SendAlexaOfferToMaster\",\"kinesisvideo:GetIceServerConfig\",\"kinesisvideo:CreateStream\"],\"Resource\": \"${channelArn}\"}]}";

        policy = policy.replace("${channelArn}", channelArn);

        StsClient stsClient = StsClient.builder()
                .credentialsProvider(getAwsCredentialsProvider())
                .region(Region.of(REGION_NAME))
                .build();

        Credentials credentials = getTemporaryCredentials(stsClient, USER_NAME, policy, 3600);

        System.out.println("accessKeyId="+credentials.accessKeyId());
        System.out.println("secretAccessKey="+credentials.secretAccessKey());
        System.out.println("sessionToken="+credentials.sessionToken());
    }

    /**
     * 获取临时Credentials
     * @param stsClient stsClient
     * @param userName userName
     * @param policy policy
     * @param durationSeconds durationSeconds
     * @return Credentials
     * @throws Exception
     */
    private static Credentials getTemporaryCredentials(StsClient stsClient, String userName, String policy, int durationSeconds) throws Exception {
        GetFederationTokenRequest getFederationTokenRequest = GetFederationTokenRequest.builder()
                .name(userName)
                .policy(policy)
                .durationSeconds(durationSeconds)
                .build();
        try {
            return stsClient.getFederationToken(getFederationTokenRequest).credentials();
        } catch (Exception e) {
            throw new Exception("Failed to get federation token: ", e);
        }
    }

    public static AwsCredentialsProvider getAwsCredentialsProvider() {

        return new AwsCredentialsProvider() {
            @Override
            public AwsCredentials resolveCredentials() {
                return new AwsCredentials() {
                    @Override
                    public String accessKeyId() {
                        return AK;
                    }

                    @Override
                    public String secretAccessKey() {
                        return SK;
                    }
                };
            }
        };
    }

}

 4、运行结果

accessKeyId=ASIA4LPNW5TYVANGARDN
secretAccessKey=FylCijk26l/g5uHPpwCJESa/J0hVVyOORxtCPy7T
sessionToken=IQoJb3JpZ2luX2VjECEaDmFwLW5vcnRoZWFzdC0yIkcwRQIhAK0ra3Pg3mOnefH/cDlo/hurf8FfNmnTdftAHkDnLXRrAiB4IAF13z9qCaozkZRZ8ZxsjR577vwjIizcmMpdlQ70CSrjAwiL//////////8BEAIaDDg0OTI5MTQzOTM0NSIMUD01WQRT0/WkbCs9KrcDYQhOe+sdagzlDbrWpd5duOyz7j5dq57hv5XmfvLjYgS7KBJHLTEkKnW03DO1MAsV1ZXEfPRAsOrdWOnxeiIanWtPRU3bWVHdQ4Zjh565aXYvJLrxOH2NnbT7zaPfvP4X7r4euUohzY+MGjGT7I2cr3jPXFfcS0njbWz6rNhnnq883qDjWL8z+G7BHFKGhjOiW9+eAe8vbd/aAjiZ4Nh91xlt17lUyI5AV9yGrCntTrUKp17GHaZbP2CVywUET9Y0iduLYXS9Bwr5HFT60RURUK7YZwcmaOT/7WwbuRoLhsuchvl7qRu891VTrCV9e+4y3B/1x1AJ5VpiXPQZ/yzphsk9qLfOyasQ90x/exvkyde9AVDFUBwPf7A9Gxz25eCfAv6BbTwrfzGCKEfNARlXQGVScXYDjpvvaNzCI4DzY3uB+mG0Mb1cHy5at7OEaxsqwlgHHfiiiSKRS/UXstQUC/j6LhxfacB3vXaeOfE4YwdXipwJxirKnjGvsLI30E8PWLLCymTHJrCow/6jbE4+FUBolo9I3lJc+ATlyxsxpn2+R988oCYetZvMi8INDW1JITlS44K2UTCfnMaKBjqZAcMqLFE+3bD8C/Zy0o0joVhkNDN41lu3RgQFMNPNJSnDboc88D6mRXbU7zS2WNdR3KnnuwpI9vEO/ttknFyb3W5dU9LEcfk6hdL3U2DxBx0pKL6bxP2cu5ADK0lkvJQuyhHSy+tR3k7gmw5i3BOiJEPeD1dJ+Q35Or2322iN9KXBqkNQByBKQ/5amZ+ylRRPe1qeP5OOXuuBUg==

 5、参考网址

  https://codingdict.com/sources/java/com.amazonaws/64702.html

posted @ 2021-09-27 17:41  mao2080  阅读(838)  评论(0编辑  收藏  举报