/// <summary> /// Instantiates STSAssumeRoleAWSCredentials which automatically assumes a specified role. /// The credentials are refreshed before expiration. /// </summary> /// <param name="sts"> /// Instance of IAmazonSecurityTokenService that will be used to make the AssumeRole service call. /// </param> /// <param name="assumeRoleRequest">Configuration for the role to assume.</param> public STSAssumeRoleAWSCredentials(IAmazonSecurityTokenService sts, AssumeRoleRequest assumeRoleRequest) { if (sts == null) throw new ArgumentNullException("sts"); if (assumeRoleRequest == null) throw new ArgumentNullException("assumeRoleRequest"); _stsClient = sts; _assumeRequest = assumeRoleRequest; PreemptExpiryTime = _defaultPreemptExpiryTime; }
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; }
/// <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> public Task<AssumeRoleResponse> AssumeRoleAsync(AssumeRoleRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AssumeRoleRequestMarshaller(); var unmarshaller = AssumeRoleResponseUnmarshaller.Instance; return InvokeAsync<AssumeRoleRequest,AssumeRoleResponse>(request, marshaller, unmarshaller, cancellationToken); }
IAsyncResult invokeAssumeRole(AssumeRoleRequest assumeRoleRequest, AsyncCallback callback, object state, bool synchronized) { IRequest irequest = new AssumeRoleRequestMarshaller().Marshall(assumeRoleRequest); var unmarshaller = AssumeRoleResponseUnmarshaller.GetInstance(); AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller); Invoke(result); return result; }
/// <summary> /// Initiates the asynchronous execution of the AssumeRole operation. /// <seealso cref="Amazon.SecurityToken.AmazonSecurityTokenService.AssumeRole"/> /// </summary> /// /// <param name="assumeRoleRequest">Container for the necessary parameters to execute the AssumeRole operation on /// AmazonSecurityTokenService.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">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> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndAssumeRole /// operation.</returns> public IAsyncResult BeginAssumeRole(AssumeRoleRequest assumeRoleRequest, AsyncCallback callback, object state) { return invokeAssumeRole(assumeRoleRequest, callback, state, false); }
/// <summary> /// <para> The <c>AssumeRole</c> action returns a set of temporary security credentials that you can use to access resources that are defined in /// the role's policy. The returned credentials consist of an Access Key ID, a Secret Access Key, and a security token. </para> <para> /// <b>Important:</b> Only IAM users can assume a role. If you use AWS account credentials to call AssumeRole, access is denied. </para> <para> /// The credentials are valid for the duration that you specified when calling <c>AssumeRole</c> , which can be from 15 minutes to 1 hour. /// </para> <para> When you assume a role, you have the privileges that are defined in the role. You can further restrict the privileges by /// passing a policy when calling <c>AssumeRole</c> . /// </para> <para> To assume a role, you must be an IAM user from a trusted entity and have permission to call <c>AssumeRole</c> . /// Trusted entites are defined when the IAM role is created. Permission to call <c>AssumeRole</c> is defined in your or your group's /// IAM policy. </para> /// </summary> /// /// <param name="assumeRoleRequest">Container for the necessary parameters to execute the AssumeRole service method on /// AmazonSecurityTokenService.</param> /// /// <returns>The response from the AssumeRole service method, as returned by AmazonSecurityTokenService.</returns> /// /// <exception cref="PackedPolicyTooLargeException"/> /// <exception cref="MalformedPolicyDocumentException"/> public AssumeRoleResponse AssumeRole(AssumeRoleRequest assumeRoleRequest) { IAsyncResult asyncResult = invokeAssumeRole(assumeRoleRequest, null, null, true); return EndAssumeRole(asyncResult); }
/// <summary> /// Initiates the asynchronous execution of the AssumeRole operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AssumeRole 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 AssumeRoleAsync(AssumeRoleRequest request, AmazonServiceCallback<AssumeRoleRequest, AssumeRoleResponse> callback, AsyncOptions options = null) { options = options == null?new AsyncOptions():options; var marshaller = new AssumeRoleRequestMarshaller(); var unmarshaller = AssumeRoleResponseUnmarshaller.Instance; Action<AmazonWebServiceRequest, AmazonWebServiceResponse, Exception, AsyncOptions> callbackHelper = null; if(callback !=null ) callbackHelper = (AmazonWebServiceRequest req, AmazonWebServiceResponse res, Exception ex, AsyncOptions ao) => { AmazonServiceResult<AssumeRoleRequest,AssumeRoleResponse> responseObject = new AmazonServiceResult<AssumeRoleRequest,AssumeRoleResponse>((AssumeRoleRequest)req, (AssumeRoleResponse)res, ex , ao.State); callback(responseObject); }; BeginInvoke<AssumeRoleRequest>(request, marshaller, unmarshaller, options, callbackHelper); }
IAsyncResult invokeAssumeRole(AssumeRoleRequest request, AsyncCallback callback, object state, bool synchronized) { var marshaller = new AssumeRoleRequestMarshaller(); var unmarshaller = AssumeRoleResponseUnmarshaller.Instance; return Invoke(request, callback, state, synchronized, marshaller, unmarshaller, signer); }
public void NoCredentialsOnContext() { var request = new AssumeRoleRequest() { DurationSeconds = 0 // invalid value for DurationSeconds - credentials will be null when retrying request }; var credentials = new STSAssumeRoleAWSCredentials(new AmazonSecurityTokenServiceClient(), request); var s3Client = new AmazonS3Client(credentials); AssertExtensions.ExpectException(() => { s3Client.ListBuckets(); }, typeof(AmazonSecurityTokenServiceException), new Regex("3 validation errors detected")); }
internal AssumeRoleResponse AssumeRole(AssumeRoleRequest request) { var task = AssumeRoleAsync(request); try { return task.Result; } catch(AggregateException e) { throw e.InnerException; } }
internal AssumeRoleResponse AssumeRole(AssumeRoleRequest request) { var task = AssumeRoleAsync(request); try { return task.Result; } catch(AggregateException e) { ExceptionDispatchInfo.Capture(e.InnerException).Throw(); return null; } }
private Amazon.SecurityToken.Model.AssumeRoleResponse CallAWSServiceOperation(IAmazonSecurityTokenService client, Amazon.SecurityToken.Model.AssumeRoleRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Security Token Service (STS)", "AssumeRole"); try { #if DESKTOP return(client.AssumeRole(request)); #elif CORECLR return(client.AssumeRoleAsync(request).GetAwaiter().GetResult()); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } }
public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.SecurityToken.Model.AssumeRoleRequest(); if (cmdletContext.DurationInSeconds != null) { request.DurationSeconds = cmdletContext.DurationInSeconds.Value; } if (cmdletContext.ExternalId != null) { request.ExternalId = cmdletContext.ExternalId; } if (cmdletContext.Policy != null) { request.Policy = cmdletContext.Policy; } if (cmdletContext.PolicyArn != null) { request.PolicyArns = cmdletContext.PolicyArn; } if (cmdletContext.RoleArn != null) { request.RoleArn = cmdletContext.RoleArn; } if (cmdletContext.RoleSessionName != null) { request.RoleSessionName = cmdletContext.RoleSessionName; } if (cmdletContext.SerialNumber != null) { request.SerialNumber = cmdletContext.SerialNumber; } if (cmdletContext.SourceIdentity != null) { request.SourceIdentity = cmdletContext.SourceIdentity; } if (cmdletContext.Tag != null) { request.Tags = cmdletContext.Tag; } if (cmdletContext.TokenCode != null) { request.TokenCode = cmdletContext.TokenCode; } if (cmdletContext.TransitiveTagKey != null) { request.TransitiveTagKeys = cmdletContext.TransitiveTagKey; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return(output); }
/// <summary> /// Initiates the asynchronous execution of the AssumeRole operation. /// <seealso cref="Amazon.SecurityToken.IAmazonSecurityTokenService.AssumeRole"/> /// </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 async Task<AssumeRoleResponse> AssumeRoleAsync(AssumeRoleRequest request, CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AssumeRoleRequestMarshaller(); var unmarshaller = AssumeRoleResponseUnmarshaller.GetInstance(); var response = await Invoke<IRequest, AssumeRoleRequest, AssumeRoleResponse>(request, marshaller, unmarshaller, signer, cancellationToken) .ConfigureAwait(continueOnCapturedContext: false); return response; }
/// <summary> /// Returns a set of temporary security credentials (consisting of an access key ID, a /// secret access key, and a security token) that you can use to access AWS resources /// that you might not normally have access to. Typically, you use <code>AssumeRole</code> /// for cross-account access or federation. /// /// /// <para> /// <b>Important:</b> You cannot call <code>AssumeRole</code> by using AWS account credentials; /// access will be denied. You must use IAM user credentials or temporary security credentials /// to call <code>AssumeRole</code>. /// </para> /// /// <para> /// For cross-account access, imagine that you own multiple accounts and need to access /// resources in each account. You could create long-term credentials in each account /// to access those resources. However, managing all those credentials and remembering /// which one can access which account can be time consuming. Instead, you can create /// one set of long-term credentials in one account and then use temporary security credentials /// to access all the other accounts by assuming roles in those accounts. For more information /// about roles, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/roles-toplevel.html">IAM /// Roles (Delegation and Federation)</a> in the <i>Using IAM</i>. /// </para> /// /// <para> /// For federation, you can, for example, grant single sign-on access to the AWS Management /// Console. If you already have an identity and authentication system in your corporate /// network, you don't have to recreate user identities in AWS in order to grant those /// user identities access to AWS. Instead, after a user has been authenticated, you call /// <code>AssumeRole</code> (and specify the role with the appropriate permissions) to /// get temporary security credentials for that user. With those temporary security credentials, /// you construct a sign-in URL that users can use to access the console. For more information, /// see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html#sts-introduction">Common /// Scenarios for Temporary Credentials</a> in the <i>Using IAM</i>. /// </para> /// /// <para> /// The temporary security credentials are valid for the duration that you specified when /// calling <code>AssumeRole</code>, which can be from 900 seconds (15 minutes) to 3600 /// seconds (1 hour). The default is 1 hour. /// </para> /// /// <para> /// Optionally, you can pass an IAM access policy to this operation. If you choose not /// to pass a policy, the temporary security credentials that are returned by the operation /// have the permissions that are defined in the access policy of the role that is being /// assumed. If you pass a policy to this operation, the temporary security credentials /// that are returned by the operation have the permissions that are allowed by both the /// access policy of the role that is being assumed, <i><b>and</b></i> the policy that /// you pass. This gives you a way to further restrict the permissions for the resulting /// temporary security credentials. You cannot use the passed policy to grant permissions /// that are in excess of those allowed by the access policy of the role that is being /// assumed. For more information, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html">Permissions /// for AssumeRole, AssumeRoleWithSAML, and AssumeRoleWithWebIdentity</a> in the <i>Using /// IAM</i>. /// </para> /// /// <para> /// To assume a role, your AWS account must be trusted by the role. The trust relationship /// is defined in the role's trust policy when the role is created. You must also have /// a policy that allows you to call <code>sts:AssumeRole</code>. /// </para> /// /// <para> /// <b>Using MFA with AssumeRole</b> /// </para> /// /// <para> /// You can optionally include multi-factor authentication (MFA) information when you /// call <code>AssumeRole</code>. This is useful for cross-account scenarios in which /// you want to make sure that the user who is assuming the role has been authenticated /// using an AWS MFA device. In that scenario, the trust policy of the role being assumed /// includes a condition that tests for MFA authentication; if the caller does not include /// valid MFA information, the request to assume the role is denied. The condition in /// a trust policy that tests for MFA authentication might look like the following example. /// </para> /// /// <para> /// <code>"Condition": {"Bool": {"aws:MultiFactorAuthPresent": true}}</code> /// </para> /// /// <para> /// For more information, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/MFAProtectedAPI.html">Configuring /// MFA-Protected API Access</a> in the <i>Using IAM</i> guide. /// </para> /// /// <para> /// To use MFA with <code>AssumeRole</code>, you pass values for the <code>SerialNumber</code> /// and <code>TokenCode</code> parameters. The <code>SerialNumber</code> value identifies /// the user's hardware or virtual MFA device. The <code>TokenCode</code> is the time-based /// one-time password (TOTP) that the MFA devices produces. /// </para> /// <member name="RoleArn" target="arnType"></member> <member name="RoleSessionName" /// target="userNameType"></member> <member name="Policy" target="sessionPolicyDocumentType"></member> /// <member name="DurationSeconds" target="roleDurationSecondsType"></member> <member /// name="ExternalId" target="externalIdType"></member> /// </summary> /// <param name="request">Container for the necessary parameters to execute the AssumeRole service method.</param> /// /// <returns>The response from the AssumeRole service method, as returned by SecurityTokenService.</returns> /// <exception cref="Amazon.SecurityToken.Model.MalformedPolicyDocumentException"> /// The request was rejected because the policy document was malformed. The error message /// describes the specific error. /// </exception> /// <exception cref="Amazon.SecurityToken.Model.PackedPolicyTooLargeException"> /// The request was rejected because the policy document was too large. The error message /// describes how big the policy document is, in packed form, as a percentage of what /// the API allows. /// </exception> public AssumeRoleResponse AssumeRole(AssumeRoleRequest request) { var marshaller = new AssumeRoleRequestMarshaller(); var unmarshaller = AssumeRoleResponseUnmarshaller.Instance; return Invoke<AssumeRoleRequest,AssumeRoleResponse>(request, marshaller, unmarshaller); }
/// <summary> /// Initiates the asynchronous execution of the AssumeRole operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AssumeRole operation on AmazonSecurityTokenServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">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> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndAssumeRole /// operation.</returns> public IAsyncResult BeginAssumeRole(AssumeRoleRequest request, AsyncCallback callback, object state) { var marshaller = new AssumeRoleRequestMarshaller(); var unmarshaller = AssumeRoleResponseUnmarshaller.Instance; return BeginInvoke<AssumeRoleRequest>(request, marshaller, unmarshaller, callback, state); }
/// <summary> /// <para> Returns a set of temporary security credentials (consisting of an access key ID, a secret access key, and a security token) that you /// can use to access AWS resources that you might not normally have access to. Typically, you use <c>AssumeRole</c> for cross-account access or /// federation. </para> <para> For cross-account access, imagine that you own multiple accounts and need to access resources in each account. /// You could create long-term credentials in each account to access those resources. However, managing all those credentials and remembering /// which one can access which account can be time consuming. Instead, you can create one set of long-term credentials in one account and then /// use temporary security credentials to access all the other accounts by assuming roles in those accounts. For more information about roles, /// see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html">Roles</a> in <i>Using IAM</i> . </para> <para> For /// federation, you can, for example, grant single sign-on access to the AWS Management Console. If you already have an identity and /// authentication system in your corporate network, you don't have to recreate user identities in AWS in order to grant those user identities /// access to AWS. Instead, after a user has been authenticated, you call <c>AssumeRole</c> (and specify the role with the appropriate /// permissions) to get temporary security credentials for that user. With those temporary security credentials, you construct a sign-in URL /// that users can use to access the console. For more information, see <a href="http://docs.aws.amazon.com/STS/latest/UsingSTS/STSUseCases.html">Scenarios for Granting Temporary Access</a> in <i>AWS Security Token /// Service</i> . </para> <para> The temporary security credentials are valid for the duration that you specified when calling <c>AssumeRole</c> /// , which can be from 900 seconds (15 minutes) to 3600 seconds (1 hour). The default is 1 hour. </para> <para>Optionally, you can pass an AWS /// IAM access policy to this operation. The temporary security credentials that are returned by the operation have the permissions that are /// associated with the access policy of the role that is being assumed, except for any permissions explicitly denied by the policy you pass. /// This gives you a way to further restrict the permissions for the federated user. These policies and any applicable resource-based policies /// are evaluated when calls to AWS are made using the temporary security credentials. </para> <para> To assume a role, your AWS account must be /// trusted by the role. The trust relationship is defined in the role's trust policy when the IAM role is created. You must also have a policy /// that allows you to call <c>sts:AssumeRole</c> . </para> <para> <b>Important:</b> You cannot call <c>AssumeRole</c> by using AWS account /// credentials; access will be denied. You must use IAM user credentials or temporary security credentials to call <c>AssumeRole</c> . </para> /// /// </summary> /// /// <param name="assumeRoleRequest">Container for the necessary parameters to execute the AssumeRole service method on /// AmazonSecurityTokenService.</param> /// /// <returns>The response from the AssumeRole service method, as returned by AmazonSecurityTokenService.</returns> /// /// <exception cref="T:Amazon.SecurityToken.Model.PackedPolicyTooLargeException" /> /// <exception cref="T:Amazon.SecurityToken.Model.MalformedPolicyDocumentException" /> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> public Task<AssumeRoleResponse> AssumeRoleAsync(AssumeRoleRequest assumeRoleRequest, CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AssumeRoleRequestMarshaller(); var unmarshaller = AssumeRoleResponseUnmarshaller.GetInstance(); return Invoke<IRequest, AssumeRoleRequest, AssumeRoleResponse>(assumeRoleRequest, marshaller, unmarshaller, signer, cancellationToken); }