public string Run(DateTime startInstant) { this.Init(); environment.awsRoleToAssume = currentProfile.RoleArn; if (currentSession.IsPresent() && sessionHelper.SessionIsActive(startInstant, currentSession) && string.IsNullOrWhiteSpace(environment.oktaProfile)) { return(currentSession.ProfileName); } var samlResponse = oktaSaml.GetSamlResponse(); AssumeRoleWithSAMLRequest assumeRequest = roleHelper.ChooseAwsRoleToAssume(samlResponse); DateTime sessionExpiry = startInstant.AddSeconds(assumeRequest.DurationSeconds - 30); AssumeRoleWithSAMLResult assumeResult = roleHelper.AssumeChosenAwsRole(assumeRequest); String profileName = profileHelper.CreateAwsProfile(assumeResult); environment.oktaProfile = profileName; environment.awsRoleToAssume = assumeRequest.RoleArn; configHelper.UpdateConfigFile(); sessionHelper.AddOrUpdateProfile(sessionExpiry); sessionHelper.UpdateCurrentSession(sessionExpiry, profileName); return(profileName); }
/// <summary> /// Gets the <see cref="SessionAWSCredentials"/> based on the specified SAML assertion and role. /// </summary> /// <param name="samlAssertion">The SAML assertion from the identity provider.</param> /// <param name="role">The role that the caller is assuming.</param> /// <param name="durationInSeconds">The duration for the AWS session credentials in seconds. Default value is 3600 seconds.</param> /// <returns>Returns a <see cref="SessionAWSCredentials"/> based on the specified SAML assertion and role.</returns> public SessionAWSCredentials GetSessionAwsCredentials(string samlAssertion, string role, int durationInSeconds = 3600) { var roles = role.Split(','); if (roles.Length > 1) { throw new ArgumentException("An invalid role was specified."); } var assumeRoleWithSamlRequest = new AssumeRoleWithSAMLRequest { SAMLAssertion = samlAssertion, PrincipalArn = roles[0], RoleArn = roles[1], DurationSeconds = durationInSeconds }; // Need to create a BasicAWSCredentials object and pass it to AmazonSecurityTokenServiceClient, // otherwise a null reference exception is thrown. Will need to look into this further as to why this happens. var basicCredential = new BasicAWSCredentials("", ""); using (var amazonSecurityTokenServiceClient = new AmazonSecurityTokenServiceClient(basicCredential)) { var amazonRoleWithSamlResponse = amazonSecurityTokenServiceClient.AssumeRoleWithSAML(assumeRoleWithSamlRequest); return(new SessionAWSCredentials(amazonRoleWithSamlResponse.Credentials.AccessKeyId, amazonRoleWithSamlResponse.Credentials.SecretAccessKey, amazonRoleWithSamlResponse.Credentials.SessionToken)); } }
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."); } }
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); }
internal AssumeRoleWithSAMLResponse AssumeRoleWithSAML(AssumeRoleWithSAMLRequest request) { AssumeRoleWithSAMLRequestMarshaller assumeRoleWithSAMLRequestMarshaller = new AssumeRoleWithSAMLRequestMarshaller(); AssumeRoleWithSAMLResponseUnmarshaller instance = AssumeRoleWithSAMLResponseUnmarshaller.Instance; return(this.Invoke <AssumeRoleWithSAMLRequest, AssumeRoleWithSAMLResponse>(request, assumeRoleWithSAMLRequestMarshaller, instance)); }
/// <summary> /// Initiates the asynchronous execution of the AssumeRoleWithSAML operation. /// <seealso cref="Amazon.SecurityToken.IAmazonSecurityTokenService"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AssumeRoleWithSAML 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 <AssumeRoleWithSAMLResponse> AssumeRoleWithSAMLAsync(AssumeRoleWithSAMLRequest request, CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AssumeRoleWithSAMLRequestMarshaller(); var unmarshaller = AssumeRoleWithSAMLResponseUnmarshaller.Instance; return(Invoke <IRequest, AssumeRoleWithSAMLRequest, AssumeRoleWithSAMLResponse>(request, marshaller, unmarshaller, signer, cancellationToken)); }
internal AssumeRoleWithSAMLResponse AssumeRoleWithSAML(AssumeRoleWithSAMLRequest request) { var marshaller = new AssumeRoleWithSAMLRequestMarshaller(); var unmarshaller = AssumeRoleWithSAMLResponseUnmarshaller.Instance; return(Invoke <AssumeRoleWithSAMLRequest, AssumeRoleWithSAMLResponse>(request, marshaller, unmarshaller)); }
/// <summary> /// Initiates the asynchronous execution of the AssumeRoleWithSAML operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AssumeRoleWithSAML 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/AssumeRoleWithSAML">REST API Reference for AssumeRoleWithSAML Operation</seealso> public virtual Task <AssumeRoleWithSAMLResponse> AssumeRoleWithSAMLAsync(AssumeRoleWithSAMLRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = AssumeRoleWithSAMLRequestMarshaller.Instance; var unmarshaller = AssumeRoleWithSAMLResponseUnmarshaller.Instance; return(InvokeAsync <AssumeRoleWithSAMLRequest, AssumeRoleWithSAMLResponse>(request, marshaller, unmarshaller, cancellationToken)); }
internal virtual AssumeRoleWithSAMLResponse AssumeRoleWithSAML(AssumeRoleWithSAMLRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = AssumeRoleWithSAMLRequestMarshaller.Instance; options.ResponseUnmarshaller = AssumeRoleWithSAMLResponseUnmarshaller.Instance; return(Invoke <AssumeRoleWithSAMLResponse>(request, options)); }
/// <summary> /// Instantiates AssumeRoleAWSCredentials which automatically assumes a specified SAML role. /// The credentials are refreshed before expiration. /// </summary> /// <param name="assumeRoleWithSamlRequest">Configuration for the SAML role to assume.</param> public AssumeRoleAWSCredentials(AssumeRoleWithSAMLRequest assumeRoleWithSamlRequest) { if (assumeRoleWithSamlRequest == null) { throw new ArgumentNullException("assumeRoleWithSamlRequest"); } _stsClient = new AmazonSecurityTokenServiceClient(new AnonymousAWSCredentials()); PreemptExpiryTime = _defaultPreemptExpiryTime; }
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); }
internal AssumeRoleWithSAMLResponse AssumeRoleWithSAML(AssumeRoleWithSAMLRequest request) { var task = AssumeRoleWithSAMLAsync(request); try { return(task.Result); } catch (AggregateException e) { ExceptionDispatchInfo.Capture(e.InnerException).Throw(); return(null); } }
/// <summary> /// 本接口(AssumeRoleWithSAML)用于根据 SAML 断言申请角色临时凭证。 /// </summary> /// <param name="req"><see cref="AssumeRoleWithSAMLRequest"/></param> /// <returns><see cref="AssumeRoleWithSAMLResponse"/></returns> public AssumeRoleWithSAMLResponse AssumeRoleWithSAMLSync(AssumeRoleWithSAMLRequest req) { JsonResponseModel <AssumeRoleWithSAMLResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "AssumeRoleWithSAML"); rsp = JsonConvert.DeserializeObject <JsonResponseModel <AssumeRoleWithSAMLResponse> >(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return(rsp.Response); }
/// <summary> /// Initiates the asynchronous execution of the AssumeRoleWithSAML operation. /// <seealso cref="Amazon.SecurityToken.IAmazonSecurityTokenService"/> /// </summary> /// <param name="request">Container for the necessary parameters to execute the AssumeRoleWithSAML operation.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes</param> /// <returns>void</returns> public void AssumeRoleWithSAMLAsync(AssumeRoleWithSAMLRequest request, AmazonServiceCallback callback, object state) { if (!AmazonInitializer.IsInitialized) { throw new Exception("AWSPrefab is not added to the scene"); } ThreadPool.QueueUserWorkItem(new WaitCallback(delegate { var marshaller = new AssumeRoleWithSAMLRequestMarshaller(); var unmarshaller = AssumeRoleWithSAMLResponseUnmarshaller.Instance; Invoke(request, callback, state, marshaller, unmarshaller, signer); })); return; }
public void AssumeRoleWithSAMLAsync(AssumeRoleWithSAMLRequest request, AmazonServiceCallback <AssumeRoleWithSAMLRequest, AssumeRoleWithSAMLResponse> callback, AsyncOptions options = null) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) options = ((options == null) ? ((object)new AsyncOptions()) : ((object)options)); AssumeRoleWithSAMLRequestMarshaller assumeRoleWithSAMLRequestMarshaller = new AssumeRoleWithSAMLRequestMarshaller(); AssumeRoleWithSAMLResponseUnmarshaller instance = AssumeRoleWithSAMLResponseUnmarshaller.Instance; Action <AmazonWebServiceRequest, AmazonWebServiceResponse, Exception, AsyncOptions> action = null; if (callback != null) { action = delegate(AmazonWebServiceRequest req, AmazonWebServiceResponse res, Exception ex, AsyncOptions ao) { AmazonServiceResult <AssumeRoleWithSAMLRequest, AssumeRoleWithSAMLResponse> val = new AmazonServiceResult <AssumeRoleWithSAMLRequest, AssumeRoleWithSAMLResponse>((AssumeRoleWithSAMLRequest)req, (AssumeRoleWithSAMLResponse)res, ex, ao.get_State()); callback.Invoke(val); }; } this.BeginInvoke <AssumeRoleWithSAMLRequest>(request, assumeRoleWithSAMLRequestMarshaller, instance, options, action); }
/// <summary> /// Initiates the asynchronous execution of the AssumeRoleWithSAML operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AssumeRoleWithSAML operation on AmazonSecurityTokenServiceClient.</param> /// <param name="callback">An Action delegate that is invoked when the operation completes.</param> /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> public void AssumeRoleWithSAMLAsync(AssumeRoleWithSAMLRequest request, AmazonServiceCallback <AssumeRoleWithSAMLRequest, AssumeRoleWithSAMLResponse> callback, AsyncOptions options = null) { options = options == null?new AsyncOptions():options; var marshaller = new AssumeRoleWithSAMLRequestMarshaller(); var unmarshaller = AssumeRoleWithSAMLResponseUnmarshaller.Instance; Action <AmazonWebServiceRequest, AmazonWebServiceResponse, Exception, AsyncOptions> callbackHelper = null; if (callback != null) { callbackHelper = (AmazonWebServiceRequest req, AmazonWebServiceResponse res, Exception ex, AsyncOptions ao) => { AmazonServiceResult <AssumeRoleWithSAMLRequest, AssumeRoleWithSAMLResponse> responseObject = new AmazonServiceResult <AssumeRoleWithSAMLRequest, AssumeRoleWithSAMLResponse>((AssumeRoleWithSAMLRequest)req, (AssumeRoleWithSAMLResponse)res, ex, ao.State); callback(responseObject); } } ; BeginInvoke <AssumeRoleWithSAMLRequest>(request, marshaller, unmarshaller, options, callbackHelper); }
public AssumeRoleWithSAMLResult AssumeChosenAwsRole(AssumeRoleWithSAMLRequest assumeRequest) { /*BasicAWSCredentials nullCredentials = new BasicAWSCredentials("", ""); * AWSCredentialsProvider nullCredentialsProvider = new AWSStaticCredentialsProvider(nullCredentials); * IAmazonSecurityTokenService sts = AmazonSecurityTokenServiceClientBuilder * .standard() * .withRegion(Regions.US_EAST_1) * .withCredentials(nullCredentialsProvider) * .build(); * * return sts.assumeRoleWithSAML(assumeRequest);*/ var config = new AmazonSecurityTokenServiceConfig { RegionEndpoint = Amazon.RegionEndpoint.EUWest1 }; var stsClient = new AmazonSecurityTokenServiceClient(config); var response = stsClient.AssumeRoleWithSAML(assumeRequest); return(response); }
private static void AssumeRoleWithSaml(String PrincipalARN, String RoleARN, String SAMLAssertionFile) { AmazonSecurityTokenServiceClient stsClient = new AmazonSecurityTokenServiceClient("", "", stsconfig); AssumeRoleWithSAMLRequest Req = new AssumeRoleWithSAMLRequest(); if (File.Exists(SAMLAssertionFile)) { String Assertion = File.ReadAllText(SAMLAssertionFile); Req.PrincipalArn = PrincipalARN; Req.RoleArn = RoleARN; Req.SAMLAssertion = Assertion; AssumeRoleWithSAMLResponse response = stsClient.AssumeRoleWithSAML(Req); Console.WriteLine("acess key id: {0}", response.Credentials.AccessKeyId); Console.WriteLine("secret key: {0}", response.Credentials.SecretAccessKey); Console.WriteLine("session token: {0}", response.Credentials.SessionToken); Console.WriteLine("Expiration: {0}", response.Credentials.Expiration); Console.WriteLine("AssumeRoleWithSAML was successful"); } else { Console.WriteLine("Assertion file missing"); } }
static async Task <AssumeRoleWithSAMLResponse> GetAssumeRoleWithSAMLResponseAsync(AmazonSecurityTokenServiceClient client, AssumeRoleWithSAMLRequest request) { var response = await client.AssumeRoleWithSAMLAsync(request); return(response); }
public Task <AssumeRoleWithSAMLResponse> AssumeRoleWithSAMLAsync(AssumeRoleWithSAMLRequest request, CancellationToken cancellationToken = new CancellationToken()) { throw new System.NotImplementedException(); }
public AssumeRoleWithSAMLRequest ChooseAwsRoleToAssume(string samlAssertion) { Dictionary <string, string> roleIdpPairs = AwsSamlRoleUtils.GetRoles(samlAssertion); List <string> roleArns = new List <string>(); string principalArn; string roleArn; if (roleIdpPairs.ContainsKey(environment.awsRoleToAssume)) { principalArn = roleIdpPairs[environment.awsRoleToAssume]; roleArn = environment.awsRoleToAssume; } else if (roleIdpPairs.Count > 1) { List <AccountOption> accountOptions = GetAvailableRoles(samlAssertion); Console.WriteLine("\nPlease choose the role you would like to assume: "); //Gather list of applicable AWS roles int i = 0; int j = -1; foreach (AccountOption accountOption in accountOptions) { Console.WriteLine(accountOption.accountName); foreach (RoleOption roleOption in accountOption.roleOptions) { roleArns.Add(roleOption.roleArn); Console.WriteLine("\t[ " + (i + 1) + " ]: " + roleOption.roleName); if (roleOption.roleArn.Equals(environment.awsRoleToAssume)) { j = i; } i++; } } if ((environment.awsRoleToAssume != null && !string.IsNullOrWhiteSpace(environment.awsRoleToAssume)) && j == -1) { Console.WriteLine("No match for role " + environment.awsRoleToAssume); } // Default to no selection int selection; // If config.properties has matching role, use it and don't prompt user to select if (j >= 0) { selection = j; Console.WriteLine("Selected option " + (j + 1) + " based on OKTA_AWS_ROLE_TO_ASSUME value"); } else { //Prompt user for role selection selection = MenuHelper.PromptForMenuSelection(roleArns.Count); } roleArn = roleArns[selection]; principalArn = roleIdpPairs[roleArn]; } else { var role = roleIdpPairs.First(); Console.WriteLine("Auto select role as only one is available : " + role.Key); roleArn = role.Key; principalArn = role.Value; } var request = new AssumeRoleWithSAMLRequest { PrincipalArn = principalArn, RoleArn = roleArn, SAMLAssertion = samlAssertion, DurationSeconds = environment.stsDuration }; return(request); }
/// <summary> /// Retrieves a set of temporary credentials for the specified role, valid for the specified timespan. /// If the SAML authentication data yield more than one role, a valid role name must be specified. /// </summary> /// <param name="stsClient">The STS client to use when making the AssumeRoleWithSAML request.</param> /// <param name="principalAndRoleArns"> /// The arns of the principal and role as returned in the SAML assertion. /// </param> /// <param name="duration">The valid timespan for the credentials.</param> /// <returns>Temporary session credentials for the specified or default role for the user.</returns> public SAMLImmutableCredentials GetRoleCredentials( IAmazonSecurityTokenService stsClient, string principalAndRoleArns, TimeSpan duration) { string roleArn = null; string principalArn = null; var swappedPrincipalAndRoleArns = string.Empty; if (!string.IsNullOrEmpty(principalAndRoleArns)) { var roleComponents = principalAndRoleArns.Split(','); if (roleComponents.Count() != 2) { throw new ArgumentException("Unknown or invalid principal and role arns format."); } swappedPrincipalAndRoleArns = roleComponents.Last() + "," + roleComponents.First(); } foreach (var s in RoleSet.Values) { if (s.Equals(principalAndRoleArns, StringComparison.OrdinalIgnoreCase) || s.Equals(swappedPrincipalAndRoleArns, StringComparison.OrdinalIgnoreCase)) { var roleComponents = s.Split(','); if (IsSamlProvider(roleComponents.First())) { //Backwards compatible format -- arn:...:saml-provider/SAML,arn:...:role/RoleName principalArn = roleComponents.First(); roleArn = roleComponents.Last(); } else { //Documented format -- arn:...:role/RoleName,arn:...:saml-provider/SAML roleArn = roleComponents.First(); principalArn = roleComponents.Last(); } break; } } if (string.IsNullOrEmpty(roleArn) || string.IsNullOrEmpty(principalArn)) { throw new ArgumentException("Unknown or invalid role specified."); } var assumeSamlRequest = new AssumeRoleWithSAMLRequest { SAMLAssertion = AssertionDocument, RoleArn = roleArn, PrincipalArn = principalArn, DurationSeconds = (int)duration.TotalSeconds }; #if NETSTANDARD //In the NetStandard SDK flavor the sync operations are internal only. var response = ((AmazonSecurityTokenServiceClient)stsClient).AssumeRoleWithSAML(assumeSamlRequest); #else var response = stsClient.AssumeRoleWithSAML(assumeSamlRequest); #endif return(new SAMLImmutableCredentials(response.Credentials.GetCredentials(), response.Credentials.Expiration.ToUniversalTime(), response.Subject)); }
private async void RefreshCredentials() { if (refreshCredentialsButton.InvokeRequired) { refreshCredentialsButton.Invoke(new Action(RefreshCredentials)); return; } refreshCredentialsButton.Enabled = false; logTextBox.Text = string.Empty; errorPanel.Visible = false; profilesListBox.Items.Clear(); _profiles.Clear(); refereshTimer.Stop(); Action <string> log = m => logTextBox.AppendText($"{DateTime.Now}: {m} {Environment.NewLine}"); try { // Authenticate against ADFS with NTLM. var endpoint = $"{adfsUrlTextBox.Text}?loginToRp={loginToRPTextBox.Text}"; var handler = new HttpClientHandler { UseCookies = true, AllowAutoRedirect = true, ClientCertificateOptions = ClientCertificateOption.Automatic }; if (useCurrentUserCheckBox.Checked) { handler.UseDefaultCredentials = true; } else { handler.Credentials = new NetworkCredential(usernameTextBox.Text, passwordTextBox.Text); } var client = new HttpClient(handler); client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"); client.DefaultRequestHeaders.Add("Connection", "Keep-Alive"); client.DefaultRequestHeaders.ExpectContinue = false; log($"Logging in as '{usernameTextBox.Text}'..."); var response = await client.GetAsync(endpoint); string body; if (useCurrentUserCheckBox.Checked) { if (response.StatusCode != HttpStatusCode.OK) { throw new InvalidOperationException("Authentication failed."); } body = await response.Content.ReadAsStringAsync(); } else { if (response.StatusCode != HttpStatusCode.Unauthorized) { throw new InvalidOperationException("Invalid ADFS Url. " + $"Visit {endpoint} in your browser to verify."); } // Need to a second time for the Network Credentials to be send. // Don't know why, but it works (and I saw firefox doing same). response = await client.GetAsync(response.RequestMessage.RequestUri); response.EnsureSuccessStatusCode(); body = await response.Content.ReadAsStringAsync(); } // Get the base64 encoded SAML response from the respons body HTML. var parser = new HtmlParser(); var htmlDocument = parser.Parse(body); var form = htmlDocument.Forms[0]; var encodedSamlResponse = ((IHtmlInputElement)form .GetElementsByTagName("input") .SingleOrDefault(e => e.GetAttribute("name") == "SAMLResponse"))?.Value; if (encodedSamlResponse == null) { throw new InvalidOperationException("Authentication failed. Check username and password." + $"Visit {endpoint} in your browser to verify."); } log("...success."); // Extract the status code and Role Attributes from the SAML response. var samlResponse = Encoding.UTF8.GetString(Convert.FromBase64String(encodedSamlResponse)); XNamespace pr = "urn:oasis:names:tc:SAML:2.0:protocol"; XNamespace ast = "urn:oasis:names:tc:SAML:2.0:assertion"; var doc = XDocument.Parse(samlResponse); var status = doc.Element(pr + "Response").Element(pr + "Status"); var statusCode = status.Element(pr + "StatusCode").Attribute("Value"); var statusMessage = status.Element(pr + "StatusMessage"); log($"SAML Status code: {statusCode}; message: {statusMessage}."); var attStatement = doc .Element(pr + "Response") .Element(ast + "Assertion") .Element(ast + "AttributeStatement"); var roles = attStatement .Elements(ast + "Attribute") .First(a => a.Attribute("Name").Value == "https://aws.amazon.com/SAML/Attributes/Role") .Elements(ast + "AttributeValue") .Select(e => e.Value.Split(',')[1]) .ToArray(); log("ADFS Defined Roles: "); foreach (var role in roles) { log($" {role}"); } // For each role, call AWS AssumeRoleWithSAML and thus create // temporary credentials. var stsClient = new AmazonSecurityTokenServiceClient(new AnonymousAWSCredentials()); var assumedRoles = new List <AssumeRoleWithSAMLResponse>(); foreach (var roleArn in roles) { log($"Assuming role {roleArn}..."); var arnParts = roleArn.Split(':'); var account = arnParts[4]; var assumeRoleWithSamlRequest = new AssumeRoleWithSAMLRequest { SAMLAssertion = encodedSamlResponse, PrincipalArn = $"arn:aws:iam::{account}:saml-provider/{samlProviderNameTextBox.Text}", RoleArn = roleArn, DurationSeconds = 3600 }; try { var assumeRoleWithSamlResponse = await stsClient.AssumeRoleWithSAMLAsync(assumeRoleWithSamlRequest); log($" AccessKeyId: {assumeRoleWithSamlResponse.Credentials.AccessKeyId}"); log($" SecretAccessKey: {assumeRoleWithSamlResponse.Credentials.SecretAccessKey}"); log($" SessionToken: {assumeRoleWithSamlResponse.Credentials.SessionToken}"); log($" Expires: {assumeRoleWithSamlResponse.Credentials.Expiration}"); assumedRoles.Add(assumeRoleWithSamlResponse); } catch (Exception ex) { log(ex.ToString()); } } // Write the temporary credentials to a the credential file (ini format) var stringBuilder = new StringBuilder(); foreach (var assumedRole in assumedRoles) { var profile = assumedRole.AssumedRoleUser.Arn.Split(':')[5].Split('/')[1]; _profiles.Add( new Profile( profile, assumedRole.Credentials.AccessKeyId, assumedRole.Credentials.SecretAccessKey, assumedRole.Credentials.SessionToken)); stringBuilder.AppendLine($"[{profile}]"); stringBuilder.AppendLine($"aws_access_key_id={assumedRole.Credentials.AccessKeyId}"); stringBuilder.AppendLine($"aws_secret_access_key={assumedRole.Credentials.SecretAccessKey}"); stringBuilder.AppendLine($"aws_session_token={assumedRole.Credentials.SessionToken}"); stringBuilder.AppendLine(); } foreach (var profile in _profiles) { profilesListBox.Items.Add(profile); } var credentialDirectory = Path.GetDirectoryName(credentialFilePathTextBox.Text); Directory.CreateDirectory(credentialDirectory); File.WriteAllText(credentialFilePathTextBox.Text, stringBuilder.ToString()); log($"Credentials written to {credentialFilePathTextBox.Text}"); } catch (Exception ex) { log(ex.ToString()); errorPanel.Visible = true; } refreshCredentialsButton.Enabled = true; _startTime = DateTime.Now; refereshTimer.Start(); }