public static Credentials GetTemporaryCredentials(string policy) { var config = new AmazonSecurityTokenServiceConfig { RegionEndpoint = RegionEndpoint.APSoutheast2 }; var client = new AmazonSecurityTokenServiceClient(config); var iamClient = new AmazonIdentityManagementServiceClient( RegionEndpoint.APSoutheast2); var iamRoleName = EC2InstanceMetadata.GetData("/iam/security-credentials"); var role = iamClient.GetRole( new GetRoleRequest() { RoleName = iamRoleName }); var assumeRoleRequest = new AssumeRoleRequest() { RoleArn = role.Role.Arn, RoleSessionName = Guid.NewGuid().ToString().Replace("-", ""), DurationSeconds = 900 }; if (!string.IsNullOrEmpty(policy)) { assumeRoleRequest.Policy = policy; } var assumeRoleResponse = client.AssumeRole(assumeRoleRequest); var credentials = assumeRoleResponse.Credentials; return(credentials); }
internal AssumeRoleResponse AssumeRole(AssumeRoleRequest request) { AssumeRoleRequestMarshaller assumeRoleRequestMarshaller = new AssumeRoleRequestMarshaller(); AssumeRoleResponseUnmarshaller instance = AssumeRoleResponseUnmarshaller.Instance; return(this.Invoke <AssumeRoleRequest, AssumeRoleResponse>(request, assumeRoleRequestMarshaller, instance)); }
private static AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret, String roleArn, String roleSessionName, String policy, ProtocolType protocolType, long durationSeconds, string region) { // try // { // 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求 IClientProfile profile = DefaultProfile.GetProfile(region, accessKeyId, accessKeySecret); DefaultAcsClient client = new DefaultAcsClient(profile); // 创建一个 AssumeRoleRequest 并设置请求参数 AssumeRoleRequest request = new AssumeRoleRequest(); //request.Encoding = "utf-8"; //request.Version = STS_API_VERSION; request.Method = MethodType.POST; //request.Protocol = protocolType; request.RoleArn = roleArn; request.RoleSessionName = roleSessionName; //request.Policy = policy; request.DurationSeconds = durationSeconds; // 发起请求,并得到response AssumeRoleResponse response = client.GetAcsResponse(request); return(response); //} //catch (ClientException e) //{ // Log.WriteErrorLog("HelperProvider::assumeRole", e.Message); // throw e; //} }
static async Task Renew() { var request = new AssumeRoleRequest { RoleArn = RoleArn, ExternalId = "Pod", RoleSessionName = "Pod" }; try { var response = await TokenService.AssumeRoleAsync(request); Log.Debug("AssumeRole response code: " + response.HttpStatusCode); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { LastRenewedUtc = LocalTime.UtcNow; FallbackCredentialsFactory.Reset(); FallbackCredentialsFactory.CredentialsGenerators.Insert(0, () => response.Credentials); } } catch (Exception ex) { Log.Error(ex, "Submitting Assume Role request failed."); throw; } }
/// <summary> /// 获取STS临时授权访问令牌 /// </summary> /// <returns></returns> public static void getSecurityToken() { try { DefaultProfile profile = DefaultProfile.GetProfile("", OssConfig.AccessKeyId, OssConfig.AccessKeySecret); DefaultAcsClient client = new DefaultAcsClient(profile); AssumeRoleRequest request = new AssumeRoleRequest(); request.Method = Aliyun.Acs.Core.Http.MethodType.POST; request.RoleArn = OssConfig.StsRoleArn; request.RoleSessionName = OssConfig.StsRoleSessionName; request.DurationSeconds = 900; AssumeRoleResponse response = client.GetAcsResponse(request); accessKeyId = response.Credentials.AccessKeyId; accessKeySecret = response.Credentials.AccessKeySecret; securityToken = response.Credentials.SecurityToken; Console.WriteLine("Expiration: " + response.Credentials.Expiration); Console.WriteLine("Access Key Id: " + response.Credentials.AccessKeyId); Console.WriteLine("Access Key Secret: " + response.Credentials.AccessKeySecret); Console.WriteLine("Security Token: " + response.Credentials.SecurityToken); Console.WriteLine("RequestId: " + response.RequestId); } catch (ClientException e) { Console.WriteLine("Failed:"); Console.WriteLine("Error code: " + e.ErrorCode); Console.WriteLine("Error message: " + e.ErrorMessage); Console.WriteLine("RequestId: " + e.RequestId); } }
protected virtual IOss GetSecurityTokenClient(AliyunFileProviderConfiguration configuration) { Check.NotNullOrWhiteSpace(configuration.RoleArn, nameof(configuration.RoleArn)); Check.NotNullOrWhiteSpace(configuration.RoleSessionName, nameof(configuration.RoleSessionName)); var cacheItem = Cache.Get(configuration.TemporaryCredentialsCacheKey); if (cacheItem == null) { IClientProfile profile = DefaultProfile.GetProfile( configuration.RegionId, configuration.AccessKeyId, configuration.AccessKeySecret); DefaultAcsClient client = new DefaultAcsClient(profile); AssumeRoleRequest request = new AssumeRoleRequest { AcceptFormat = FormatType.JSON, //eg:acs:ram::$accountID:role/$roleName RoleArn = configuration.RoleArn, RoleSessionName = configuration.RoleSessionName, //Set the validity period of the temporary access credential, the unit is s, the minimum is 900, and the maximum is 3600. default 3600 DurationSeconds = configuration.DurationSeconds, //Set additional permission policy of Token; when acquiring Token, further reduce the permission of Token by setting an additional permission policy Policy = configuration.Policy.IsNullOrEmpty() ? null : configuration.Policy, }; var response = client.GetAcsResponse(request); cacheItem = SetTemporaryCredentialsCache(configuration, response.Credentials); } return(new OssClient( configuration.Endpoint, StringEncryptionService.Decrypt(cacheItem.AccessKeyId), StringEncryptionService.Decrypt(cacheItem.AccessKeySecret), StringEncryptionService.Decrypt(cacheItem.SecurityToken))); }
private static IRestRequest SignWithSTSKeysAndSecurityToken(IRestRequest restRequest, string host, string roleARN, string accessKey, string secretKey) { AssumeRoleResponse response = null; using (var STSClient = new AmazonSecurityTokenServiceClient(accessKey, secretKey, RegionEndpoint.EUWest1)) { var req = new AssumeRoleRequest() { RoleArn = roleARN, DurationSeconds = 950, //put anything you want here RoleSessionName = Guid.NewGuid().ToString() }; response = STSClient.AssumeRoleAsync(req, new CancellationToken()).Result; } //auth step 3: dönen değerler bizim yeni tokenlarımızı... var awsAuthenticationCredentials = new AWSAuthenticationCredentials { AccessKeyId = response.Credentials.AccessKeyId, SecretKey = response.Credentials.SecretAccessKey, Region = REGION }; restRequest.AddHeader("x-amz-security-token", response.Credentials.SessionToken); return(new AWSSigV4Signer(awsAuthenticationCredentials).Sign(restRequest, host)); }
static async Task Renew() { Log.Info("Requesting AssumeRole: " + RoleArn + "..."); var request = new AssumeRoleRequest { RoleArn = RoleArn, DurationSeconds = (int)12.Hours().TotalSeconds, ExternalId = "Pod", RoleSessionName = "Pod" }; try { var response = await TokenServiceClient.AssumeRoleAsync(request); Log.Debug("AssumeRole response code: " + response.HttpStatusCode); var credentials = response.Credentials; FallbackCredentialsFactory.Reset(); FallbackCredentialsFactory.CredentialsGenerators.Insert(0, () => { Log.Debug("Generating credentials => " + credentials.AccessKeyId.Substring(20) + " of total : " + FallbackCredentialsFactory.CredentialsGenerators.Count); return(credentials); } ); Log.Debug("Obtained assume role credentials." + credentials.AccessKeyId.Substring(20)); } catch (Exception ex) { Log.Error(ex, "Submitting Assume Role request failed."); throw; } }
public Credentials GetTemporaryCredentials() { BasicAWSCredentials creds = new BasicAWSCredentials(Environment.GetEnvironmentVariable("AWS_ACCESS_KEY_ID"), Environment.GetEnvironmentVariable("AWS_SECRET_ACCESS_KEY")); try { var stsClient = client.getStsClient(creds); using (stsClient) { var assumeRoleTokenRequest = new AssumeRoleRequest { DurationSeconds = 3600, // seconds RoleArn = Environment.GetEnvironmentVariable("S3_ASSUME_ROLE_ARN"), //get from env var RoleSessionName = "Session" }; AssumeRoleResponse assumeRoleTokenResponse = client.assumeRole(stsClient, assumeRoleTokenRequest); Credentials credentials = assumeRoleTokenResponse.Credentials; return(credentials); } } catch (Exception ex) { throw ex; } }
/// <summary> /// Used to modify cloudformation cross account artifacts to bucket owner full access. /// </summary> /// <param name="jobEvent">CodePipeline event.</param> /// <param name="context">Lambda Context</param> /// <returns>Job success of the Lambda</returns> public async Task <AmazonWebServiceResponse> FixCloudFormationOutputArtifactAcl(CodePipelineJobEvent jobEvent, ILambdaContext context) { var jobId = jobEvent.CodePipelineJob.Id; context.Logger.LogLine($"JobId: {jobId}"); using (var codePipelineClient = new AmazonCodePipelineClient()) using (var stsClient = new AmazonSecurityTokenServiceClient()) { try { var jobData = jobEvent.CodePipelineJob.Data; // Assume the role in the cloudformation account that screwed up the bucket permissions // for the output object var userParameters = jobData.ActionConfiguration.Configuration["UserParameters"]; var paramDict = JsonConvert.DeserializeObject <Dictionary <string, string> >(userParameters); var roleArn = paramDict["RoleArn"]; var assumeRoleRequest = new AssumeRoleRequest { RoleArn = roleArn, RoleSessionName = "codepipeline", DurationSeconds = 900 }; var assumeRoleResponse = await stsClient.AssumeRoleAsync(assumeRoleRequest); // Setup an S3 Client with the sts creds var s3Client = new AmazonS3Client(assumeRoleResponse.Credentials); // Update the ACLs of the input artifacts foreach (var inputArtifact in jobData.InputArtifacts) { var bucketName = inputArtifact.Location.S3Location.BucketName; var bucketKey = inputArtifact.Location.S3Location.ObjectKey; context.Logger.LogLine($"Fixing {bucketName}/{bucketKey}"); var putObjectAclRequest = new PutACLRequest { BucketName = bucketName, CannedACL = S3CannedACL.BucketOwnerFullControl, Key = bucketKey }; await s3Client.PutACLAsync(putObjectAclRequest); } // Send the success response var successResultRequest = new PutJobSuccessResultRequest { JobId = jobId }; return(await codePipelineClient.PutJobSuccessResultAsync(successResultRequest)); } catch (Exception ex) { // Send the failure response and log return(await DoException(codePipelineClient, ex, jobId, context)); } } }
public void TestAssumeRoleCredentials() { var clientId = Guid.NewGuid(); var roleArn = _role.Arn; const string sessionName = "NetUser"; // sleep for IAM data to propagate UtilityMethods.Sleep(TimeSpan.FromSeconds(10)); var sts = new AmazonSecurityTokenServiceClient(_userCredentials); UtilityMethods.Sleep(TimeSpan.FromSeconds(60)); var request = new AssumeRoleRequest { RoleArn = roleArn, RoleSessionName = sessionName, DurationSeconds = 3600, ExternalId = clientId.ToString() }; var credentials = new STSAssumeRoleAWSCredentials(sts, request); var client = new AmazonIdentityManagementServiceClient(credentials); var response = client.ListRolesAsync().Result; Assert.IsNotNull(response); }
public void OutputLogInfoTestInValid() { string format = "{code}|{pid}|{start_time}"; var logger = new Logger(loggerPath: EnvironmentUtil.GetHomePath() + EnvironmentUtil.GetOSSlash() + "log.txt", template: format); SerilogHelper.SetLogger(logger); var request = new AssumeRoleRequest { Url = "https://www.alibabacloud.com" }; var response = new HttpResponse(); long executeTime = 100; string startTime = DateTime.Now.ToString(); Assert.Throws <ClientException>(() => { SerilogHelper.LogInfo(request, null, executeTime, startTime); }); SerilogHelper.CloseLogger(); Assert.False(SerilogHelper.EnableLogger); SerilogHelper.LogInfo(request, null, 100, "100"); }
static void Main(string[] args) { string accessKey = "AKIAYASBUYUORND23YUN"; string secretKey = "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"; RegionEndpoint region = RegionEndpoint.APSoutheast2; AWSCredentials cred = new BasicAWSCredentials(accessKey, secretKey); IAmazonSecurityTokenService stsClient = new AmazonSecurityTokenServiceClient(cred, region); AssumeRoleRequest stsRequest = new AssumeRoleRequest(); stsRequest.DurationSeconds = 910; stsRequest.RoleArn = "arn:aws:iam::550967231773:role/MyAssumeRole"; stsRequest.RoleSessionName = "MyAssumeRolesessionFromDotNet"; AssumeRoleResponse temporaryCred = stsClient.AssumeRoleAsync(stsRequest).Result; IAmazonS3 client = new AmazonS3Client(temporaryCred.Credentials, region); ListBucketsRequest request = new ListBucketsRequest(); ListBucketsResponse response = client.ListBucketsAsync(request).Result; foreach (S3Bucket b in response.Buckets) { Console.WriteLine(b.BucketName); } Console.ReadLine(); }
public async Task AssumeRoleAsync(UserAccountExtended userAccount, UserRoleExtended userRole, CancellationToken cancellationToken) { if (userAccount == null) { throw new ArgumentNullException(nameof(userAccount)); } if (userRole == null) { throw new ArgumentNullException(nameof(userRole)); } if (cancellationToken == null) { throw new ArgumentNullException(nameof(cancellationToken)); } using (var stsClient = new AmazonSecurityTokenServiceClient(userAccount.AwsCredentials, _config)) { var request = new AssumeRoleRequest { RoleArn = Role(userRole.AwsAccountId, userRole.Role), RoleSessionName = userRole.AwsAccountLabel }; var role2 = await stsClient.AssumeRoleAsync(request, cancellationToken) .ConfigureAwait(false); var tempAccessKeyId = role2.Credentials.AccessKeyId; var tempSessionToken = role2.Credentials.SessionToken; var tempSecretAccessKey = role2.Credentials.SecretAccessKey; userRole.AwsCredentials = new SessionAWSCredentials(tempAccessKeyId, tempSecretAccessKey, tempSessionToken); } }
internal AssumeRoleResponse AssumeRole(AssumeRoleRequest request) { var marshaller = new AssumeRoleRequestMarshaller(); var unmarshaller = AssumeRoleResponseUnmarshaller.Instance; return(Invoke <AssumeRoleRequest, AssumeRoleResponse>(request, marshaller, unmarshaller)); }
/// <summary> /// <see cref="ICoreAmazonSTS"/> /// </summary> /// <param name="roleArn"></param> /// <param name="roleSessionName"></param> /// <param name="options"></param> /// <returns></returns> AssumeRoleImmutableCredentials ICoreAmazonSTS.CredentialsFromAssumeRoleAuthentication(string roleArn, string roleSessionName, AssumeRoleAWSCredentialsOptions options) { try { var request = new AssumeRoleRequest { RoleArn = roleArn, RoleSessionName = roleSessionName }; if (options != null) { request.ExternalId = options.ExternalId; request.SerialNumber = options.MfaSerialNumber; request.TokenCode = options.MfaTokenCode; request.Policy = options.Policy; if (options.DurationSeconds.HasValue) { request.DurationSeconds = options.DurationSeconds.Value; } } var response = AssumeRole(request); return(new AssumeRoleImmutableCredentials(response.Credentials.AccessKeyId, response.Credentials.SecretAccessKey, response.Credentials.SessionToken, response.Credentials.Expiration)); } catch (Exception e) { var msg = "Error calling AssumeRole for role " + roleArn; var exception = new AmazonClientException(msg, e); Logger.GetLogger(typeof(AmazonSecurityTokenServiceClient)).Error(exception, exception.Message); throw exception; } }
/// <summary> /// Initiates the asynchronous execution of the AssumeRole operation. /// <seealso cref="Amazon.SecurityToken.IAmazonSecurityTokenService"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AssumeRole operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task <AssumeRoleResponse> AssumeRoleAsync(AssumeRoleRequest request, CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AssumeRoleRequestMarshaller(); var unmarshaller = AssumeRoleResponseUnmarshaller.Instance; return(Invoke <IRequest, AssumeRoleRequest, AssumeRoleResponse>(request, marshaller, unmarshaller, signer, cancellationToken)); }
static async Task Main() { // Create the SecurityToken client and then display the identity of the // default user. var roleArnToAssume = "arn:aws:iam::123456789012:role/testAssumeRole"; var client = new Amazon.SecurityToken.AmazonSecurityTokenServiceClient(REGION); // Get and display the information about the identity of the default user. var callerIdRequest = new GetCallerIdentityRequest(); var caller = await client.GetCallerIdentityAsync(callerIdRequest); Console.WriteLine($"Original Caller: {caller.Arn}"); // Create the request to use with the AssumeRoleAsync call. var assumeRoleReq = new AssumeRoleRequest() { DurationSeconds = 1600, RoleSessionName = "Session1", RoleArn = roleArnToAssume }; var assumeRoleRes = await client.AssumeRoleAsync(assumeRoleReq); // Now create a new client based on the credentials of the caller assuming the role. var client2 = new AmazonSecurityTokenServiceClient(credentials: assumeRoleRes.Credentials); // Get and display information about the caller that has assumed the defined role. var caller2 = await client2.GetCallerIdentityAsync(callerIdRequest); Console.WriteLine($"AssumedRole Caller: {caller2.Arn}"); }
public AssumeRoleResponse GetTemporaryCredentials(string awsAccount) { try { using (var stsClient = new AmazonSecurityTokenServiceClient()) { LambdaLogger.Log($"Begin assume role for AWS account with ID {awsAccount}"); AssumeRoleRequest request = new AssumeRoleRequest { RoleArn = $"arn:aws:iam::{awsAccount}:role/{Environment.GetEnvironmentVariable("AWS_ROLE_NAME_FOR_STS_API_GATEWAY_GET")}", DurationSeconds = 900, //15 mins, which is the minimum accepted RoleSessionName = "Session-for-retrieving-API-name" }; LambdaLogger.Log($"Role ARN in request: {request.RoleArn}"); var credentialsResponse = stsClient.AssumeRoleAsync(request).GetAwaiter().GetResult(); LambdaLogger.Log($"Credentials for role with ARN {request.RoleArn} retrieved for user - {credentialsResponse.AssumedRoleUser}"); return(credentialsResponse); } } catch (Exception ex) { LambdaLogger.Log($"An error occurred while assuming role for AWS account with ID {awsAccount}. Message: {ex.Message}"); throw; } }
static async Task Renew() { Log.Info("Requesting AssumeRole: " + RoleArn + "..."); var request = new AssumeRoleRequest { RoleArn = RoleArn, DurationSeconds = (int)12.Hours().TotalSeconds, ExternalId = "Pod", RoleSessionName = "Pod" }; try { using (var client = new AmazonSecurityTokenServiceClient()) { var response = await client.AssumeRoleAsync(request); Log.Debug("AssumeRole response code: " + response.HttpStatusCode); var credentials = response.Credentials; FallbackCredentialsFactory.Reset(); FallbackCredentialsFactory.CredentialsGenerators.Insert(0, () => credentials); Log.Debug("Obtained assume role credentials."); } } catch (Exception ex) { Log.Error(ex, "Submitting Assume Role request failed."); throw; } }
internal static async Task <StopInstancesResponse> StopEc2InstanceAsync(IConfiguration Configuration, string User, string AccountName, string InstanceId) { try { var accountKey = LoadAwsAccounts(Configuration).SingleOrDefault(x => x.AccountName == AccountName); var accountRegion = RegionEndpoint.GetBySystemName(accountKey.Region); var stsClient = new AmazonSecurityTokenServiceClient(); var sessionName = string.Format(ResourceStrings.StopAction, User, accountKey.AccountName, DateTime.Now.Ticks.ToString()); sessionName = sessionName.Length > 63 ? sessionName.Substring(0, 63) : sessionName; var assumeRoleRequest = new AssumeRoleRequest { RoleArn = accountKey.RoleArn, RoleSessionName = sessionName, DurationSeconds = 900 }; var stsResponse = await stsClient.AssumeRoleAsync(assumeRoleRequest); var instanceIdAsList = new List <string> { InstanceId }; var stopRequest = new StopInstancesRequest(instanceIdAsList); var ec2Client = new AmazonEC2Client(stsResponse.Credentials, accountRegion); var response = ec2Client.StopInstancesAsync(stopRequest); ec2Client.Dispose(); stsClient.Dispose(); return(await response); } catch (Exception e) { throw new Exception(string.Format(ErrorStrings.RebootEc2InstanceError, InstanceId, e.Message), e.InnerException); } }
public void TestAssumeRoleCredentials() { var clientId = Guid.NewGuid(); var roleArn = _role.Arn; const string sessionName = "NetUser"; // sleep for IAM data to propagate Thread.Sleep(TimeSpan.FromSeconds(10)); var sts = new AmazonSecurityTokenServiceClient(_userCredentials); Thread.Sleep(TimeSpan.FromSeconds(60)); var request = new AssumeRoleRequest { RoleArn = roleArn, RoleSessionName = sessionName, DurationSeconds = 3600, ExternalId = clientId.ToString() }; // keep this unit test even though STSAssumeRoleAWSCredentials is obsolete #pragma warning disable 0618 var credentials = new STSAssumeRoleAWSCredentials(sts, request); var client = new AmazonIdentityManagementServiceClient(credentials); var response = client.ListRoles(); Assert.IsNotNull(response); }
public void RoleArnTest() { AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest(); string source = "foo"; assumeRoleRequest.RoleArn = source; Assert.Equal(source, assumeRoleRequest.RoleArn); }
/// <summary> /// Initiates the asynchronous execution of the AssumeRole operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AssumeRole operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRole">REST API Reference for AssumeRole Operation</seealso> public virtual Task <AssumeRoleResponse> AssumeRoleAsync(AssumeRoleRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = AssumeRoleRequestMarshaller.Instance; var unmarshaller = AssumeRoleResponseUnmarshaller.Instance; return(InvokeAsync <AssumeRoleRequest, AssumeRoleResponse>(request, marshaller, unmarshaller, cancellationToken)); }
public void PolicyTest() { AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest(); string source = "foo"; assumeRoleRequest.Policy = source; Assert.Equal(source, assumeRoleRequest.Policy); }
public void RoleSessionNameTest() { var assumeRoleRequest = new AssumeRoleRequest(); var source = "foo"; assumeRoleRequest.RoleSessionName = source; Assert.Equal(source, assumeRoleRequest.RoleSessionName); }
public void RoleArnTest() { var assumeRoleRequest = new AssumeRoleRequest(); var source = "foo"; assumeRoleRequest.RoleArn = source; Assert.Equal(source, assumeRoleRequest.RoleArn); }
public void PolicyTest() { var assumeRoleRequest = new AssumeRoleRequest(); var source = "foo"; assumeRoleRequest.Policy = source; Assert.Equal(source, assumeRoleRequest.Policy); }
public void DurationSecondsTest() { var assumeRoleRequest = new AssumeRoleRequest(); var source = 10000000000; assumeRoleRequest.DurationSeconds = source; Assert.Equal(source, assumeRoleRequest.DurationSeconds); }
private static async Task Main(string[] args) { var credentials = new BasicAWSCredentials("censored", "censored"); var client = new AmazonSecurityTokenServiceClient(credentials); var request = new GetSessionTokenRequest { DurationSeconds = 900 }; var response = await client.GetSessionTokenAsync(request); Console.WriteLine(response.Credentials.AccessKeyId); Console.WriteLine(response.Credentials.SecretAccessKey); var credentials2 = response.Credentials; var client2 = new AmazonSecurityTokenServiceClient(credentials2); var req = new AssumeRoleRequest(); req.DurationSeconds = 900; req.RoleArn = "arn:aws:s3:::my-test-bucket-coolrocket"; req.RoleSessionName = "user1"; //var x = await client2.AssumeRoleAsync(req); var s3client = new AmazonS3Client(response.Credentials, RegionEndpoint.EUCentral1); var r = new GetObjectRequest(); r.BucketName = "my-test-bucket-coolrocket"; r.Key = "user1/big_buck_bunny.mp4"; //r.Path = "user1/big_buck_bunny.mp4"; var temp = await s3client.GetObjectAsync(r); //using (var client = new AmazonMediaStoreClient(credentials, RegionEndpoint.EUCentral1)) //using (var storeDataClient = await CreateStoreDataClientAsync(client: client, containerName: "test", credentials: credentials)) //{ // //var user = await CreateIamUserAsync(credentials, "zero"); // //await DeleteIamUserAsync(credentials, "zero"); // //await DeleteObjectFromContainerAsync(storeDataClient, "id3/sample.mp4"); // var t = await GetContainerPolicyAsync(client, "test"); // //await PutObjectToContainerAsync(storeDataClient, "path2/sample.mp4"); // //var stream = await GetObjectAsync(storeDataClient, "path1/sample.mp4"); //} Console.ReadKey(); }
public static AssumeRoleResponse.Credentials_ GetSecurityToken() { if (credentials!=null&&(DateTime.Now-_timeStamp).Seconds<30) { //防止请求过于频繁,设置5分钟请求一次。 return credentials; } // 构建一个 Aliyun Client, 用于发起请求 // 构建Aliyun Client时需要设置AccessKeyId和AccessKeySevcret // STS是Global Service, API入口位于杭州, 这里Region填写"cn-hangzhou" IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret); var client = new DefaultAcsClient(profile); // 构造AssumeRole请求 var request = new AssumeRoleRequest(); // 指定角色Arn request.RoleArn = "acs:ram::1724377057077130:role/myfirstrole"; request.RoleSessionName = "alice"; // 可以设置Token有效期,可选参数,默认3600秒; request.DurationSeconds = 3600; // 可以设置Token的附加Policy,可以在获取Token时,通过额外设置一个Policy进一步减小Token的权限; // request.Policy="<policy-content>" try { AssumeRoleResponse response = client.GetAcsResponse(request); //Console.WriteLine("AccessKeyId: " + response.Credentials.AccessKeyId); //Console.WriteLine("AccessKeySecret: " + response.Credentials.AccessKeySecret); //Console.WriteLine("SecurityToken: " + response.Credentials.SecurityToken); ////Token过期时间;服务器返回UTC时间,这里转换成北京时间显示; //Console.WriteLine("Expiration: " + DateTime.Parse(response.Credentials.Expiration).ToLocalTime()); credentials = response.Credentials; _timeStamp = DateTime.Now; return credentials; } catch (Exception ex) { return null; //记录错误日志 } }
/// <summary> /// 获取临时访问权限 /// </summary> /// <returns></returns> private static AssumeRoleResponse.Credentials_ GetSecurityToken() { // 构建一个 Aliyun Client, 用于发起请求 // 构建Aliyun Client时需要设置AccessKeyId和AccessKeySevcret // STS是Global Service, API入口位于杭州, 这里Region填写"cn-hangzhou" IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret); DefaultAcsClient client = new DefaultAcsClient(profile); // 构造AssumeRole请求 AssumeRoleRequest request = new AssumeRoleRequest(); // 指定角色Arn request.RoleArn = "acs:ram::1724377057077130:role/myfirstrole"; request.RoleSessionName = "alice"; // 可以设置Token有效期,可选参数,默认3600秒; //request.DurationSeconds = 3600; // 可以设置Token的附加Policy,可以在获取Token时,通过额外设置一个Policy进一步减小Token的权限; // request.Policy="<policy-content>" try { AssumeRoleResponse response = client.GetAcsResponse(request); Console.WriteLine("AccessKeyId: " + response.Credentials.AccessKeyId); Console.WriteLine("AccessKeySecret: " + response.Credentials.AccessKeySecret); Console.WriteLine("SecurityToken: " + response.Credentials.SecurityToken); //Token过期时间;服务器返回UTC时间,这里转换成北京时间显示; Console.WriteLine("Expiration: " + DateTime.Parse(response.Credentials.Expiration).ToLocalTime()); return response.Credentials; } catch (Exception ex) { Console.Write(ex.ToString()); } return null; }