public SessionAWSCredentials GetSamlRoleCredentails(string samlAssertion, string awsRole) { string[] role = awsRole.Split(','); AssumeRoleWithSAMLRequest samlRequest = new AssumeRoleWithSAMLRequest(); samlRequest.SAMLAssertion = samlAssertion; samlRequest.RoleArn = role[1]; samlRequest.PrincipalArn = role[0]; samlRequest.DurationSeconds = 3600; AmazonSecurityTokenServiceClient sts; AssumeRoleWithSAMLResponse samlResponse; try { sts = new AmazonSecurityTokenServiceClient(); samlResponse = sts.AssumeRoleWithSAML(samlRequest); } catch { sts = new AmazonSecurityTokenServiceClient("a", "b", "c"); samlResponse = sts.AssumeRoleWithSAML(samlRequest); } SessionAWSCredentials sessionCredentials = new SessionAWSCredentials( samlResponse.Credentials.AccessKeyId, samlResponse.Credentials.SecretAccessKey, samlResponse.Credentials.SessionToken); return sessionCredentials; }
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}"); }
private void CreateAndCheckTestBucket() { TestBucketIsReady = false; USEast1Client = new AmazonS3Client(RegionEndpoint.USEast1); USWest1Client = new AmazonS3Client(RegionEndpoint.USWest1); var sessionCredentials = new AmazonSecurityTokenServiceClient().GetSessionToken().Credentials; USEast1ClientWithSessionCredentials = new AmazonS3Client(sessionCredentials, RegionEndpoint.USEast1); TestBucket = USWest1Client.ListBuckets().Buckets.Find(bucket => bucket.BucketName.StartsWith(BucketPrefix)); if (TestBucket == null) { // add ticks to bucket name because the bucket namespace is shared globally var bucketName = BucketPrefix + DateTime.Now.Ticks; // Create the bucket but don't run the test. // If the bucket is ready the next time this test runs we'll test then. USWest1Client.PutBucket(new PutBucketRequest() { BucketRegion = S3Region.USW1, BucketName = bucketName, }); } else if (TestBucket.CreationDate.AddHours(TemporaryRedirectMaxExpirationHours) < DateTime.Now) { BucketRegionDetector.BucketRegionCache.Clear(); TestBucketIsReady = true; } }
static void Main(string[] args) { var roleArnToAssume = "arn:aws:iam::123456789012:role/testAssumeRole"; var principalArn = "arn:aws:iam::123456789012:saml-provider/testSamlProvider"; string base64SamlFile = "saml.xml.b64"; if (File.Exists(base64SamlFile)) { string samlAssertion = File.ReadAllText(base64SamlFile); var stsClient1 = new Amazon.SecurityToken.AmazonSecurityTokenServiceClient(new AnonymousAWSCredentials()); var assumeRoleReq = new AssumeRoleWithSAMLRequest(); assumeRoleReq.DurationSeconds = 3600; assumeRoleReq.RoleArn = roleArnToAssume; assumeRoleReq.PrincipalArn = principalArn; assumeRoleReq.SAMLAssertion = samlAssertion; var assumeRoleRes = GetAssumeRoleWithSAMLResponseAsync(client: stsClient1, request: assumeRoleReq); var stsClient2 = new Amazon.SecurityToken.AmazonSecurityTokenServiceClient(credentials: assumeRoleRes.Result.Credentials); var getCallerIdReq = new GetCallerIdentityRequest(); var assumedRoleIdentity = GetCallerIdentityResponseAsync(client: stsClient2, request: getCallerIdReq); Console.WriteLine("AssumedRole Caller: " + assumedRoleIdentity.Result.Arn.ToString()); } else { Console.WriteLine("Base64 Encoded SAML File: " + base64SamlFile + " does not exist in this directory."); } }
static void Main(string[] args) { var client = new Amazon.SecurityToken.AmazonSecurityTokenServiceClient(); var getCallerIdReq = new GetCallerIdentityRequest(); var caller = GetCallerIdentityResponseAsync(client: client, request: getCallerIdReq); Console.WriteLine("Caller Identity ARN: " + caller.Result.Arn.ToString()); }
public override void ViewDidLoad () { base.ViewDidLoad (); var client = new AmazonSecurityTokenServiceClient (new BasicAWSCredentials (ACCESS_KEY, SECRET_KEY), Amazon.RegionEndpoint.USEast1); var response = client.GetSessionToken (); Console.WriteLine (response.Credentials.AccessKeyId); }
public void HappyCaseWithSessionToken() { var stsClient = new AmazonSecurityTokenServiceClient(RegionEndpoint.USWest2); var response = stsClient.GetSessionToken(new GetSessionTokenRequest { DurationSeconds = 900 }); AssertPreSignedUrl(SynthesizeSpeechUtil.GeneratePresignedUrl(response.Credentials, RegionEndpoint.USWest2, GetRequest())); }
public virtual Credentials AppMode_AssumeRole(AmazonSecurityTokenServiceClient stsClient, string roleArn, string roleSessionName) { Credentials credentials = null; var assumeRoleRequest = new AssumeRoleRequest { RoleArn = roleArn, RoleSessionName = roleSessionName }; bool retry; int sleepSeconds = 3; DateTime startTime = DateTime.Now; do { try { AssumeRoleResponse assumeRoleResponse = stsClient.AssumeRole(assumeRoleRequest); credentials = assumeRoleResponse.Credentials; retry = false; } catch (AmazonServiceException ase) { if (ase.ErrorCode.Equals("AccessDenied")) { if (sleepSeconds > 20) { // If we've gotten here it's because we've retried a few times and are still getting the same error. // Just rethrow the error to stop waiting. The exception will bubble up. Console.WriteLine(" [Aborted AssumeRole Operation]"); retry = false; } else { // Write a period to the screen so we have a visual indication that we're in our retry logic. Console.Write("."); // Sleep before retrying. Thread.Sleep(TimeSpan.FromSeconds(sleepSeconds)); // Increment the retry interval. sleepSeconds = sleepSeconds*3; retry = true; } } else { throw; } } } while (retry); return credentials; }
protected virtual void Dispose(bool disposing) { if (!_isDisposed) { if (disposing && _stsClient != null) { _stsClient.Dispose(); _stsClient = null; } _isDisposed = true; } }
public STSAssumeRoleAWSCredentials(AssumeRoleWithSAMLRequest assumeRoleWithSamlRequest) : this() { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown if (assumeRoleWithSamlRequest == null) { throw new ArgumentNullException("assumeRoleWithSamlRequest"); } _stsClient = new AmazonSecurityTokenServiceClient(new AnonymousAWSCredentials()); _assumeSamlRequest = assumeRoleWithSamlRequest; this.set_PreemptExpiryTime(_defaultPreemptExpiryTime); }
public STSAssumeRoleAWSCredentials(IAmazonSecurityTokenService sts, AssumeRoleRequest assumeRoleRequest) : this() { if (sts == null) { throw new ArgumentNullException("sts"); } if (assumeRoleRequest == null) { throw new ArgumentNullException("assumeRoleRequest"); } _stsClient = (AmazonSecurityTokenServiceClient)sts; _assumeRequest = assumeRoleRequest; this.set_PreemptExpiryTime(_defaultPreemptExpiryTime); }
protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); // Set our view from the "main" layout resource SetContentView (Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById<Button> (Resource.Id.myButton); button.Click += delegate { button.Text = string.Format ("{0} clicks!", count++); }; var client = new AmazonSecurityTokenServiceClient (new BasicAWSCredentials (ACCESS_KEY, SECRET_KEY), Amazon.RegionEndpoint.USEast1); var response = client.GetSessionToken (); Console.WriteLine (response.Credentials.AccessKeyId); }
static void Main(string[] args) { var roleArnToAssume = "arn:aws:iam::123456789012:role/testAssumeRole"; var client = new Amazon.SecurityToken.AmazonSecurityTokenServiceClient(); var getCallerIdReq = new GetCallerIdentityRequest(); var caller = GetCallerIdentityResponseAsync(client: client, request: getCallerIdReq); Console.WriteLine("Original Caller: " + caller.Result.Arn.ToString()); var assumeRoleReq = new AssumeRoleRequest(); assumeRoleReq.DurationSeconds = 1600; assumeRoleReq.RoleSessionName = "Session1"; assumeRoleReq.RoleArn = roleArnToAssume; var assumeRoleRes = GetAssumeRoleResponseAsync(client: client, request: assumeRoleReq); var client2 = new Amazon.SecurityToken.AmazonSecurityTokenServiceClient(credentials: assumeRoleRes.Result.Credentials); var caller2 = GetCallerIdentityResponseAsync(client: client2, request: getCallerIdReq); Console.WriteLine("AssumedRole Caller: " + caller2.Result.Arn.ToString()); }
AssumeRoleWithWebIdentityResponse GetAssumeRoleWithWebIdentityResponse( AssumeRoleWithWebIdentityRequest assumeRoleWithWebIdentityRequest) { // Start with Anonymous AWS Credentials and get temporary credentials. var stsClient = new AmazonSecurityTokenServiceClient( new AnonymousAWSCredentials()); assumeRoleWithWebIdentityRequest.DurationSeconds = 3600; assumeRoleWithWebIdentityRequest.RoleSessionName = "MySession"; return stsClient.AssumeRoleWithWebIdentity( assumeRoleWithWebIdentityRequest); }
public Deployer(AwsConfiguration awsConfiguration) { _awsEndpoint = awsConfiguration.AwsEndpoint; _bucket = awsConfiguration.Bucket; _assumeRoleTrustDocument = awsConfiguration.AssumeRoleTrustDocument; _iamRolePolicyDocument = awsConfiguration.IamRolePolicyDocument; AWSCredentials credentials; if (isArn(awsConfiguration.RoleName)) { var securityTokenServiceClient = new AmazonSecurityTokenServiceClient(awsConfiguration.AwsEndpoint); var assumeRoleResult = securityTokenServiceClient.AssumeRole(new AssumeRoleRequest { RoleArn = awsConfiguration.RoleName, DurationSeconds = 3600, RoleSessionName = "Net2User", ExternalId = Guid.NewGuid().ToString() }); Credentials stsCredentials = assumeRoleResult.Credentials; SessionAWSCredentials sessionCredentials = new SessionAWSCredentials(stsCredentials.AccessKeyId, stsCredentials.SecretAccessKey, stsCredentials.SessionToken); credentials = sessionCredentials; _role = new AssumedRole(assumeRoleResult.AssumedRoleUser); } else { credentials = awsConfiguration.Credentials ?? new EnvironmentAWSCredentials(); } _codeDeployClient = new AmazonCodeDeployClient( credentials, new AmazonCodeDeployConfig { RegionEndpoint = awsConfiguration.AwsEndpoint, ProxyHost = awsConfiguration.ProxyHost, ProxyPort = awsConfiguration.ProxyPort }); _cloudFormationClient = new AmazonCloudFormationClient( credentials, new AmazonCloudFormationConfig { RegionEndpoint = awsConfiguration.AwsEndpoint, ProxyHost = awsConfiguration.ProxyHost, ProxyPort = awsConfiguration.ProxyPort }); _s3Client = new AmazonS3Client( credentials, new AmazonS3Config { RegionEndpoint = awsConfiguration.AwsEndpoint, ProxyHost = awsConfiguration.ProxyHost, ProxyPort = awsConfiguration.ProxyPort }); _iamClient = new AmazonIdentityManagementServiceClient( credentials, new AmazonIdentityManagementServiceConfig { RegionEndpoint = awsConfiguration.AwsEndpoint, ProxyHost = awsConfiguration.ProxyHost, ProxyPort = awsConfiguration.ProxyPort }); _autoScalingClient = new AmazonAutoScalingClient( credentials, new AmazonAutoScalingConfig { RegionEndpoint = awsConfiguration.AwsEndpoint, ProxyHost = awsConfiguration.ProxyHost, ProxyPort = awsConfiguration.ProxyPort }); }
/// <summary> /// Perform the AppMode operations by assuming the dev and prod roles, and checking for permissions. /// </summary> /// <param name="labVariables">The data.</param> public void AppMode_Run(LabVariables labVariables) { var credentials = new BasicAWSCredentials( ConfigurationManager.AppSettings["appModeAWSAccessKey"], ConfigurationManager.AppSettings["appModeAWSSecretKey"]); Credentials devCredentials = null, prodCredentials = null; using (var stsClient = new AmazonSecurityTokenServiceClient(credentials, RegionEndpoint)) { Console.WriteLine("Assuming developer role to retrieve developer session credentials."); devCredentials = LabCode.AppMode_AssumeRole(stsClient, labVariables.DevelopmentRoleArn, "dev_session"); if (devCredentials == null) { Console.WriteLine("No developer credentials returned. AccessDenied."); return; } Console.WriteLine("\nAssuming production role to retrieve production session credentials."); prodCredentials = LabCode.AppMode_AssumeRole(stsClient, labVariables.ProductionRoleArn, "prod_session"); if (prodCredentials == null) { Console.WriteLine("No production credentials returned. AccessDenied."); return; } } using (var devS3Client = LabCode.AppMode_CreateS3Client(devCredentials, RegionEndpoint)) { using (var prodS3Client = LabCode.AppMode_CreateS3Client(prodCredentials, RegionEndpoint)) { Console.WriteLine("\nTesting Developer Session..."); var devSession = new SessionAWSCredentials( devCredentials.AccessKeyId, devCredentials.SecretAccessKey, devCredentials.SessionToken); Console.WriteLine(" IAM: {0}", OptionalLabCode.AppMode_TestIamAccess(RegionEndpoint, devSession) ? "Accessible." : "Inaccessible."); Console.WriteLine(" SQS: {0}", OptionalLabCode.AppMode_TestSqsAccess(RegionEndpoint, devSession) ? "Accessible." : "Inaccessible."); Console.WriteLine(" SNS: {0}", OptionalLabCode.AppMode_TestSnsAccess(RegionEndpoint, devSession) ? "Accessible." : "Inaccessible."); Console.WriteLine(" S3:"); foreach (string bucketName in labVariables.BucketNames) { TestS3Client(devS3Client, bucketName); } Console.WriteLine("\nTesting Production Session..."); var prodSession = new SessionAWSCredentials( prodCredentials.AccessKeyId, prodCredentials.SecretAccessKey, prodCredentials.SessionToken); Console.WriteLine(" IAM: {0}", OptionalLabCode.AppMode_TestIamAccess(RegionEndpoint, prodSession) ? "Accessible." : "Inaccessible."); Console.WriteLine(" SQS: {0}", OptionalLabCode.AppMode_TestSqsAccess(RegionEndpoint, prodSession) ? "Accessible." : "Inaccessible."); Console.WriteLine(" SNS: {0}", OptionalLabCode.AppMode_TestSnsAccess(RegionEndpoint, prodSession) ? "Accessible." : "Inaccessible."); Console.WriteLine(" S3:"); foreach (string bucketName in labVariables.BucketNames) { TestS3Client(prodS3Client, bucketName); } } } }
public void SetupClient(Hashtable State) { //Creating AmazonSecurityTokenServiceClient, using Access and Secret keys from web.config AmazonSecurityTokenServiceClient stsClient = new AmazonSecurityTokenServiceClient(); //Creating RefreshingSessionAWSCredentials and initializing AmazonDynamoDBClient RefreshingSessionAWSCredentials sessionCredentials = new RefreshingSessionAWSCredentials(stsClient); State["DynamoDBClient"] = new AmazonDynamoDBClient(sessionCredentials); }
private static AmazonSecurityTokenService ConstructSTSClient(AWSCredentials credentials, AmazonSecurityTokenServiceConfig config) { using (ImmutableCredentials immmutableCredentials = credentials.GetCredentials()) { if (immmutableCredentials.UseToken) throw new ArgumentException("Session credentials cannot be used to create refreshing session credentials"); AmazonSecurityTokenServiceClient stsClient; if (immmutableCredentials.UseSecureStringForSecretKey) { stsClient = new AmazonSecurityTokenServiceClient(immmutableCredentials.AccessKey, GetClearSecretKey(immmutableCredentials.SecureSecretKey), config); } else { stsClient = new AmazonSecurityTokenServiceClient(immmutableCredentials.AccessKey, immmutableCredentials.ClearSecretKey, config); } return stsClient; } }
/// <summary> /// Assume the specified role. /// Hint: Use the AssumeRole() method of the client object. /// Optional: You may see an eventual consistency issue here. The AssumeRole permissions may not /// have propagated through the system yet which could prevent us from assuming the role. Check for /// an AmazonServiceException with an ErrorCode of "AccessDenied" and retry the assume role operation /// after a short wait (with exponential back-off on retries). If you decide to stop retrying, /// return null. /// </summary> /// <param name="stsClient">The STS client object.</param> /// <param name="roleArn">The ARN of the role to assume.</param> /// <param name="roleSessionName">The name to use as the role session name.</param> /// <returns>The role credentials, or null if there was a problem.</returns> public override Credentials AppMode_AssumeRole(AmazonSecurityTokenServiceClient stsClient, string roleArn, string roleSessionName) { //TODO: Replace this call to the base class with your own method implementation. return base.AppMode_AssumeRole(stsClient, roleArn, roleSessionName); }