Exemplo n.º 1
0
        private AssumeRoleWithWebIdentityRequest SetupAssumeRoleWithWebIdentityRequest(string webIdentityToken, string roleArn,
                                                                                       string roleSessionName, AssumeRoleWithWebIdentityCredentialsOptions options)
        {
            var request = new AssumeRoleWithWebIdentityRequest
            {
                WebIdentityToken = webIdentityToken,
                RoleArn          = roleArn,
                RoleSessionName  = roleSessionName
            };

            if (options != null)
            {
                request.ProviderId = options.ProviderId;
                request.PolicyArns = options.PolicyArns?.Select((arn) => new PolicyDescriptorType {
                    Arn = arn
                }).ToList();
                request.Policy = options.Policy;
                if (options.DurationSeconds.HasValue)
                {
                    request.DurationSeconds = options.DurationSeconds.Value;
                }
            }

            return(request);
        }
Exemplo n.º 2
0
        internal AssumeRoleWithWebIdentityResponse AssumeRoleWithWebIdentity(AssumeRoleWithWebIdentityRequest request)
        {
            var marshaller   = new AssumeRoleWithWebIdentityRequestMarshaller();
            var unmarshaller = AssumeRoleWithWebIdentityResponseUnmarshaller.Instance;

            return(Invoke <AssumeRoleWithWebIdentityRequest, AssumeRoleWithWebIdentityResponse>(request, marshaller, unmarshaller));
        }
Exemplo n.º 3
0
        public async Task <IActionResult> AssumeRoleAsync()
        {
            if (!HttpContext.User.Identity.IsAuthenticated)
            {
                return(new OkObjectResult("you have to sign in to access AWS resources"));
            }

            try
            {
                var assumeRoleRequest = new AssumeRoleWithWebIdentityRequest
                {
                    RoleArn          = "arn:aws:iam::628654266155:role/acme_app_access_s3",
                    RoleSessionName  = "testsession",
                    WebIdentityToken = GetOktaTokenMiddleware.OktaToken,
                };

                var stsServiceClient = new AmazonSecurityTokenServiceClient(new BasicAWSCredentials("****", "*****"), RegionEndpoint.USEast2);
                var response         = await stsServiceClient.AssumeRoleWithWebIdentityAsync(assumeRoleRequest);

                //var response = await stsServiceClient.ListRoles()
                return(new OkObjectResult($"key = {response.Credentials.AccessKeyId}   security = {response.Credentials.SecretAccessKey}"));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Exemplo n.º 4
0
        protected void GenerateNewCredentialsAsync(AmazonServiceCallback callback)
        {
            AmazonServiceResult voidResult = new AmazonServiceResult(null, null);

            IdentityProvider.RefreshAsync(delegate(AmazonServiceResult refreshResult)
            {
                if (refreshResult.Exception != null)
                {
                    voidResult.Exception = refreshResult.Exception;
                    AmazonMainThreadDispatcher.ExecCallback(callback, voidResult);
                    return;
                }


                // Pick role to use, depending on Logins
                string roleArn = UnAuthRoleArn;
                if (IdentityProvider.Logins.Count > 0)
                {
                    roleArn = AuthRoleArn;
                }
                if (string.IsNullOrEmpty(roleArn))
                {
                    voidResult.Exception = new AmazonServiceException(
                        new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
                                                                    "Unable to determine Role ARN. AuthRoleArn = [{0}], UnAuthRoleArn = [{1}], Logins.Count = {2}",
                                                                    AuthRoleArn, UnAuthRoleArn, IdentityProvider.Logins.Count)));
                    AmazonMainThreadDispatcher.ExecCallback(callback, voidResult);
                    return;
                }

                // Assume role with Open Id Token
                var assumeRequest = new AssumeRoleWithWebIdentityRequest
                {
                    WebIdentityToken = IdentityProvider.GetCurrentOpenIdToken(),
                    RoleArn          = roleArn,
                    RoleSessionName  = "UnityProviderSession",
                    DurationSeconds  = DefaultDurationSeconds
                };

                sts.AssumeRoleWithWebIdentityAsync(assumeRequest, delegate(AmazonServiceResult result)
                {
                    if (result.Exception != null)
                    {
                        voidResult.Exception = result.Exception;
                        AmazonLogging.LogError(AmazonLogging.AmazonLoggingLevel.Errors, "STS", result.Exception.Message);
                        AmazonMainThreadDispatcher.ExecCallback(callback, voidResult);
                        return;
                    }
                    AssumeRoleWithWebIdentityResponse assumeRoleWithWebIdentityResponse = result.Response as AssumeRoleWithWebIdentityResponse;
                    this._currentState = new CredentialsRefreshState
                    {
                        Credentials = assumeRoleWithWebIdentityResponse.Credentials.GetCredentials(),
                        Expiration  = assumeRoleWithWebIdentityResponse.Credentials.Expiration
                    };
                    // success - FinalResponse
                    AmazonMainThreadDispatcher.ExecCallback(callback, voidResult);
                    return;
                }, null);
            }, null);
        }
        private Amazon.SecurityToken.Model.Credentials GetStsCredentials(AssumeRoleWithWebIdentityRequest assumeRequest)
        {
            var assumeResult = Amazon.Runtime.Internal.Util.AsyncHelpers.RunSync <AssumeRoleWithWebIdentityResponse>(() => sts.AssumeRoleWithWebIdentityAsync(assumeRequest));
            var credentials  = assumeResult.Credentials;

            return(credentials);
        }
Exemplo n.º 6
0
        private Amazon.SecurityToken.Model.Credentials GetStsCredentials(AssumeRoleWithWebIdentityRequest assumeRequest)
        {
            var ars = new AutoResetEvent(false);

            Amazon.SecurityToken.Model.Credentials credentials = null;
            Exception exception = null;

            sts.AssumeRoleWithWebIdentityAsync(assumeRequest, (assumeResult) =>
            {
                if (assumeResult.Exception != null)
                {
                    exception = assumeResult.Exception;
                }
                else
                {
                    credentials = assumeResult.Response.Credentials;
                }

                ars.Set();
            });
            ars.WaitOne();

            if (exception != null)
            {
                throw exception;
            }

            return(credentials);
        }
Exemplo n.º 7
0
        internal AssumeRoleWithWebIdentityResponse AssumeRoleWithWebIdentity(AssumeRoleWithWebIdentityRequest request)
        {
            AssumeRoleWithWebIdentityRequestMarshaller    assumeRoleWithWebIdentityRequestMarshaller = new AssumeRoleWithWebIdentityRequestMarshaller();
            AssumeRoleWithWebIdentityResponseUnmarshaller instance = AssumeRoleWithWebIdentityResponseUnmarshaller.Instance;

            return(this.Invoke <AssumeRoleWithWebIdentityRequest, AssumeRoleWithWebIdentityResponse>(request, assumeRoleWithWebIdentityRequestMarshaller, instance));
        }
        private async System.Threading.Tasks.Task <CredentialsRefreshState> GetCredentialsForRoleAsync(string roleArn)
        {
            CredentialsRefreshState credentialsState;
            // Retrieve Open Id Token
            // (Reuses existing IdentityId or creates a new one)
            var identity = await GetIdentityIdAsync(RefreshIdentityOptions.Refresh).ConfigureAwait(false);

            var getTokenRequest = new GetOpenIdTokenRequest {
                IdentityId = identity
            };

            // If logins are set, pass them to the GetOpenId call
            if (Logins.Count > 0)
            {
                getTokenRequest.Logins = Logins;
            }

            bool retry = false;
            GetOpenIdTokenResponse getTokenResult = null;

            try
            {
                getTokenResult = await cib.GetOpenIdTokenAsync(getTokenRequest).ConfigureAwait(false);
            }
            catch (AmazonCognitoIdentityException e)
            {
                if (ShouldRetry(e))
                {
                    retry = true;
                }
                else
                {
                    throw;
                }
            }

            if (retry)
            {
                return(await GetCredentialsForRoleAsync(roleArn).ConfigureAwait(false));
            }

            string token = getTokenResult.Token;

            // IdentityId may have changed, save the new value
            UpdateIdentity(getTokenResult.IdentityId);

            // Assume role with Open Id Token
            var assumeRequest = new AssumeRoleWithWebIdentityRequest
            {
                WebIdentityToken = token,
                RoleArn          = roleArn,
                RoleSessionName  = "NetProviderSession",
                DurationSeconds  = DefaultDurationSeconds
            };
            var credentials = (await sts.AssumeRoleWithWebIdentityAsync(assumeRequest).ConfigureAwait(false)).Credentials;

            // Return new refresh state (credentials and expiration)
            credentialsState = new CredentialsRefreshState(credentials.GetCredentials(), credentials.Expiration);
            return(credentialsState);
        }
Exemplo n.º 9
0
        // Retrieves credentials for the specific role, by making a call to STS
        private CredentialsRefreshState GetCredentialsForRole(string roleArn)
        {
            CredentialsRefreshState credentialsState;
            // Retrieve Open Id Token
            // (Reuses existing IdentityId or creates a new one)
            var getTokenRequest = new GetOpenIdTokenRequest {
                IdentityId = GetIdentityId()
            };

            // If logins are set, pass them to the GetOpenId call
            if (Logins.Count > 0)
            {
                getTokenRequest.Logins = Logins;
            }
            var    getTokenResult = GetOpenId(getTokenRequest);
            string token          = getTokenResult.Token;

            // IdentityId may have changed, save the new value
            UpdateIdentity(getTokenResult.IdentityId, true);

            // Assume role with Open Id Token
            var assumeRequest = new AssumeRoleWithWebIdentityRequest
            {
                WebIdentityToken = token,
                RoleArn          = roleArn,
                RoleSessionName  = "NetProviderSession",
                DurationSeconds  = DefaultDurationSeconds
            };
            var credentials = GetStsCredentials(assumeRequest);

            credentialsState = new CredentialsRefreshState(credentials.GetCredentials(), credentials.Expiration);
            return(credentialsState);
        }
Exemplo n.º 10
0
        private Amazon.SecurityToken.Model.Credentials GetStsCredentials(AssumeRoleWithWebIdentityRequest assumeRequest)
        {
            var assumeResult = sts.AssumeRoleWithWebIdentity(assumeRequest);
            var credentials  = assumeResult.Credentials;

            return(credentials);
        }
Exemplo n.º 11
0
        private void GetCredentialsForRoleWebGL(string roleArn, Action <CredentialsRefreshState> callback)
        {
            CredentialsRefreshState credentialsState;

            // Retrieve Open Id Token
            // (Reuses existing IdentityId or creates a new one)
            this.GetIdentityIdWebGL(RefreshIdentityOptions.Refresh, identity =>
            {
                var getTokenRequest = new GetOpenIdTokenRequest {
                    IdentityId = identity
                };
                // If logins are set, pass them to the GetOpenId call
                if (Logins.Count > 0)
                {
                    getTokenRequest.Logins = Logins;
                }

                GetOpenIdWebGL(getTokenRequest, (getTokenResult, e) =>
                {
                    bool retry = false;

                    if (e is AmazonCognitoIdentityException)
                    {
                        if (ShouldRetry(e as AmazonCognitoIdentityException))
                        {
                            retry = true;
                        }
                        else
                        {
                            throw e;
                        }
                    }

                    if (retry)
                    {
                        GetCredentialsForRoleWebGL(roleArn, callback);
                        return;
                    }

                    string token = getTokenResult.Token;

                    // IdentityId may have changed, save the new value
                    UpdateIdentity(getTokenResult.IdentityId);

                    // Assume role with Open Id Token
                    var assumeRequest = new AssumeRoleWithWebIdentityRequest
                    {
                        WebIdentityToken = token,
                        RoleArn          = roleArn,
                        RoleSessionName  = "NetProviderSession",
                        DurationSeconds  = DefaultDurationSeconds
                    };
                    var credentials = GetStsCredentials(assumeRequest);

                    credentialsState = new CredentialsRefreshState(credentials.GetCredentials(), credentials.Expiration);
                    callback(credentialsState);
                });
            });
        }
        // Retrieves credentials for the specific role, by making a call to STS
        private CredentialsRefreshState GetCredentialsForRole(string roleArn)
        {
            CredentialsRefreshState credentialsState;
            // Retrieve Open Id Token
            // (Reuses existing IdentityId or creates a new one)
            var identity        = this.GetIdentityId(RefreshIdentityOptions.Refresh);
            var getTokenRequest = new GetOpenIdTokenRequest {
                IdentityId = identity
            };

            // If logins are set, pass them to the GetOpenId call
            if (Logins.Count > 0)
            {
                getTokenRequest.Logins = Logins;
            }

            bool retry = false;
            GetOpenIdTokenResponse getTokenResult = null;

            try
            {
                getTokenResult = GetOpenId(getTokenRequest);
            }
            catch (AmazonCognitoIdentityException e)
            {
                if (ShouldRetry(e))
                {
                    retry = true;
                }
                else
                {
                    throw;
                }
            }

            if (retry)
            {
                return(GetCredentialsForRole(roleArn));
            }

            string token = getTokenResult.Token;

            // IdentityId may have changed, save the new value
            UpdateIdentity(getTokenResult.IdentityId);

            // Assume role with Open Id Token
            var assumeRequest = new AssumeRoleWithWebIdentityRequest
            {
                WebIdentityToken = token,
                RoleArn          = roleArn,
                RoleSessionName  = "NetProviderSession",
                DurationSeconds  = DefaultDurationSeconds
            };
            var credentials = GetStsCredentials(assumeRequest);

            credentialsState = new CredentialsRefreshState(credentials.GetCredentials(), credentials.Expiration);
            return(credentialsState);
        }
        internal virtual AssumeRoleWithWebIdentityResponse AssumeRoleWithWebIdentity(AssumeRoleWithWebIdentityRequest request)
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = AssumeRoleWithWebIdentityRequestMarshaller.Instance;
            options.ResponseUnmarshaller = AssumeRoleWithWebIdentityResponseUnmarshaller.Instance;

            return(Invoke <AssumeRoleWithWebIdentityResponse>(request, options));
        }
        IAsyncResult invokeAssumeRoleWithWebIdentity(AssumeRoleWithWebIdentityRequest assumeRoleWithWebIdentityRequest, AsyncCallback callback, object state, bool synchronized)
        {
            IRequest    irequest     = new AssumeRoleWithWebIdentityRequestMarshaller().Marshall(assumeRoleWithWebIdentityRequest);
            var         unmarshaller = AssumeRoleWithWebIdentityResponseUnmarshaller.GetInstance();
            AsyncResult result       = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);

            Invoke(result);
            return(result);
        }
Exemplo n.º 15
0
        private static async Task ListObjectsAsync()
        {
            try
            {
                Console.WriteLine("Listing objects stored in a bucket");
                var    roleArn = "arn:aws:iam::291738886548:role/s3webreaderrole";
                string CREDENTIAL_FILE_JSON = "/path/to/svc.json";


                // Get the idtoken as string and use it in a standard credential
                // var targetAudience = "https://sts.amazonaws.com/";
                // var idToken = await getGoogleOIDCToken(targetAudience, CREDENTIAL_FILE_JSON);
                // var rawIdToken = await idToken.GetAccessTokenAsync().ConfigureAwait(false);
                // SessionAWSCredentials tempCredentials = await getTemporaryCredentialsAsync(rawIdToken, roleArn, "testsession");
                // Console.WriteLine(tempCredentials.GetCredentials().Token);
                // using (s3Client = new AmazonS3Client(tempCredentials, bucketRegion))

                // or create a usable GoogleCredential to wrap that
                ServiceAccountCredential saCredential;
                using (var fs = new FileStream(CREDENTIAL_FILE_JSON, FileMode.Open, FileAccess.Read))
                {
                    saCredential = ServiceAccountCredential.FromServiceAccountData(fs);
                }
                var getSessionTokenRequest = new AssumeRoleWithWebIdentityRequest
                {
                    RoleSessionName = "testsession",
                    RoleArn         = roleArn
                };
                var cc = new GoogleCompatCredentials(saCredential, "https://sts.amazonaws.com/", getSessionTokenRequest);
                using (s3Client = new AmazonS3Client(cc, bucketRegion))

                //  *****************
                {
                    var listObjectRequest = new ListObjectsRequest
                    {
                        BucketName = bucketName
                    };
                    ListObjectsResponse response = await s3Client.ListObjectsAsync(listObjectRequest);

                    List <S3Object> objects = response.S3Objects;
                    foreach (S3Object o in objects)
                    {
                        Console.WriteLine("Object  = {0}", o.Key);
                    }
                }
            }
            catch (AmazonS3Exception s3Exception)
            {
                Console.WriteLine(s3Exception.Message, s3Exception.InnerException);
            }
            catch (AmazonSecurityTokenServiceException stsException)
            {
                Console.WriteLine(stsException.Message, stsException.InnerException);
            }
        }
        public object Execute(ExecutorContext context)
        {
            var cmdletContext = context as CmdletContext;
            // create request
            var request = new AssumeRoleWithWebIdentityRequest();

            if (cmdletContext.RoleArn != null)
            {
                request.RoleArn = cmdletContext.RoleArn;
            }
            if (cmdletContext.RoleSessionName != null)
            {
                request.RoleSessionName = cmdletContext.RoleSessionName;
            }
            if (cmdletContext.WebIdentityToken != null)
            {
                request.WebIdentityToken = cmdletContext.WebIdentityToken;
            }
            if (cmdletContext.ProviderId != null)
            {
                request.ProviderId = cmdletContext.ProviderId;
            }
            if (cmdletContext.Policy != null)
            {
                request.Policy = cmdletContext.Policy;
            }
            if (cmdletContext.DurationSeconds != null)
            {
                request.DurationSeconds = cmdletContext.DurationSeconds.Value;
            }

            // issue call
            var          client = Client ?? CreateClient();
            CmdletOutput output;

            try
            {
                var    response       = CallAWSServiceOperation(client, request);
                object pipelineOutput = cmdletContext.Select(response, this);;
                output = new CmdletOutput
                {
                    PipelineOutput  = pipelineOutput,
                    ServiceResponse = response
                };
            }
            catch (Exception e)
            {
                output = new CmdletOutput {
                    ErrorResponse = e
                };
            }

            return(output);
        }
Exemplo n.º 17
0
        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));
        }
Exemplo n.º 18
0
        internal AssumeRoleWithWebIdentityResponse AssumeRoleWithWebIdentity(AssumeRoleWithWebIdentityRequest request)
        {
            var task = AssumeRoleWithWebIdentityAsync(request);

            try
            {
                return(task.Result);
            }
            catch (AggregateException e)
            {
                ExceptionDispatchInfo.Capture(e.InnerException).Throw();
                return(null);
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Initiates the asynchronous execution of the AssumeRoleWithWebIdentity operation.
        /// <seealso cref="Amazon.SecurityToken.IAmazonSecurityTokenService"/>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the AssumeRoleWithWebIdentity operation.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes</param>
        /// <returns>void</returns>
        public void AssumeRoleWithWebIdentityAsync(AssumeRoleWithWebIdentityRequest 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 AssumeRoleWithWebIdentityRequestMarshaller();
                var unmarshaller = AssumeRoleWithWebIdentityResponseUnmarshaller.Instance;
                Invoke(request, callback, state, marshaller, unmarshaller, signer);
            }));
            return;
        }
Exemplo n.º 20
0
        private CredentialsRefreshState GetCredentialsForRole(string roleArn)
        {
            string text = GetIdentityId(RefreshIdentityOptions.Refresh);
            GetOpenIdTokenRequest getOpenIdTokenRequest = new GetOpenIdTokenRequest
            {
                IdentityId = text
            };

            if (Logins.Count > 0)
            {
                getOpenIdTokenRequest.Logins = Logins;
            }
            bool flag = false;
            GetOpenIdTokenResponse getOpenIdTokenResponse = null;

            try
            {
                getOpenIdTokenResponse = GetOpenId(getOpenIdTokenRequest);
            }
            catch (AmazonCognitoIdentityException e)
            {
                if (!ShouldRetry(e))
                {
                    throw;
                }
                flag = true;
            }
            if (flag)
            {
                return(GetCredentialsForRole(roleArn));
            }
            string token = getOpenIdTokenResponse.Token;

            UpdateIdentity(getOpenIdTokenResponse.IdentityId);
            AssumeRoleWithWebIdentityRequest assumeRequest = new AssumeRoleWithWebIdentityRequest
            {
                WebIdentityToken = token,
                RoleArn          = roleArn,
                RoleSessionName  = "NetProviderSession",
                DurationSeconds  = DefaultDurationSeconds
            };

            Amazon.SecurityToken.Model.Credentials stsCredentials = GetStsCredentials(assumeRequest);
            return(new CredentialsRefreshState(stsCredentials.GetCredentials(), stsCredentials.Expiration));
        }
Exemplo n.º 21
0
        public void AssumeRoleWithWebIdentityAsync(AssumeRoleWithWebIdentityRequest request, AmazonServiceCallback <AssumeRoleWithWebIdentityRequest, AssumeRoleWithWebIdentityResponse> 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));
            AssumeRoleWithWebIdentityRequestMarshaller    assumeRoleWithWebIdentityRequestMarshaller = new AssumeRoleWithWebIdentityRequestMarshaller();
            AssumeRoleWithWebIdentityResponseUnmarshaller instance = AssumeRoleWithWebIdentityResponseUnmarshaller.Instance;
            Action <AmazonWebServiceRequest, AmazonWebServiceResponse, Exception, AsyncOptions> action = null;

            if (callback != null)
            {
                action = delegate(AmazonWebServiceRequest req, AmazonWebServiceResponse res, Exception ex, AsyncOptions ao)
                {
                    AmazonServiceResult <AssumeRoleWithWebIdentityRequest, AssumeRoleWithWebIdentityResponse> val = new AmazonServiceResult <AssumeRoleWithWebIdentityRequest, AssumeRoleWithWebIdentityResponse>((AssumeRoleWithWebIdentityRequest)req, (AssumeRoleWithWebIdentityResponse)res, ex, ao.get_State());
                    callback.Invoke(val);
                };
            }
            this.BeginInvoke <AssumeRoleWithWebIdentityRequest>(request, assumeRoleWithWebIdentityRequestMarshaller, instance, options, action);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Initiates the asynchronous execution of the AssumeRoleWithWebIdentity operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the AssumeRoleWithWebIdentity 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 AssumeRoleWithWebIdentityAsync(AssumeRoleWithWebIdentityRequest request, AmazonServiceCallback <AssumeRoleWithWebIdentityRequest, AssumeRoleWithWebIdentityResponse> callback, AsyncOptions options = null)
        {
            options = options == null?new AsyncOptions():options;
            var marshaller   = new AssumeRoleWithWebIdentityRequestMarshaller();
            var unmarshaller = AssumeRoleWithWebIdentityResponseUnmarshaller.Instance;
            Action <AmazonWebServiceRequest, AmazonWebServiceResponse, Exception, AsyncOptions> callbackHelper = null;

            if (callback != null)
            {
                callbackHelper = (AmazonWebServiceRequest req, AmazonWebServiceResponse res, Exception ex, AsyncOptions ao) => {
                    AmazonServiceResult <AssumeRoleWithWebIdentityRequest, AssumeRoleWithWebIdentityResponse> responseObject
                        = new AmazonServiceResult <AssumeRoleWithWebIdentityRequest, AssumeRoleWithWebIdentityResponse>((AssumeRoleWithWebIdentityRequest)req, (AssumeRoleWithWebIdentityResponse)res, ex, ao.State);
                    callback(responseObject);
                }
            }
            ;
            BeginInvoke <AssumeRoleWithWebIdentityRequest>(request, marshaller, unmarshaller, options, callbackHelper);
        }
Exemplo n.º 23
0
        static async Task Main(string[] args)
        {
            var awsOptions = new AWSOptions();

            using (var cognito = new AmazonCognitoIdentityProviderClient(RegionEndpoint.EUWest1))
            {
                var initAuthRequest = new AdminInitiateAuthRequest
                {
                    AuthFlow       = AuthFlowType.ADMIN_NO_SRP_AUTH,
                    AuthParameters = new Dictionary <string, string>
                    {
                    },
                    UserPoolId = "eu-west-1_BJ8QvSs1g",
                    ClientId   = "5ive4k9rhvvo776p7rppa5gcd5"
                };

                var response = await cognito.AdminInitiateAuthAsync(initAuthRequest);

                var challengeResponse = new AdminRespondToAuthChallengeRequest
                {
                    ChallengeName = response.ChallengeName,
                    Session       = response.Session,
                    ClientId      = "Filer",
                    UserPoolId    = "Services"
                };

                var authResponse = await cognito.AdminRespondToAuthChallengeAsync(challengeResponse);

                using (var securityTokenProvider = new AmazonSecurityTokenServiceClient())
                {
                    var assumeRoleRequest = new AssumeRoleWithWebIdentityRequest
                    {
                        RoleArn = "",

                        WebIdentityToken = authResponse.AuthenticationResult.AccessToken
                    };

                    var roleCreds = await securityTokenProvider.AssumeRoleWithWebIdentityAsync(assumeRoleRequest);

                    awsOptions.Credentials = roleCreds.Credentials;
                }
            }
        }
Exemplo n.º 24
0
        public AssumeRoleWithWebIdentityResponse GetTemporaryCredentialUsingFacebook(
            string client_id,
            string role)
        {
            string query = "https://www.facebook.com/dialog/oauth?" +
                           string.Format("client_id={0}&", client_id) +
                           "response_type=token&" +
                           "redirect_uri=https://www.facebook.com/connect/login_success.html";

            AssumeRoleWithWebIdentityRequest assumeRoleWithWebIdentityRequest =
                new AssumeRoleWithWebIdentityRequest()
            {
                ProviderId       = "graph.facebook.com",
                WebIdentityToken = GetToken("access_token", query),
                RoleArn          = role,
            };

            return(GetAssumeRoleWithWebIdentityResponse(assumeRoleWithWebIdentityRequest));
        }
Exemplo n.º 25
0
        public AssumeRoleWithWebIdentityResponse GetTemporaryCredentialUsingGoogle2(
            string client_id,
            string client_secret,
            string role)
        {
            string query = "https://accounts.google.com/o/oauth2/auth?" +
                           string.Format("client_id={0}&", client_id) +
                           "response_type=code&" +
                           "scope=email%20profile&" +
                           "redirect_uri=http://www.padisetty.com";

            string id_token = null;

            using (var wc = new WebClient())
            {
                var data = new NameValueCollection();

                data["code"]          = GetToken("code", query);
                data["client_id"]     = client_id;
                data["client_secret"] = client_secret;
                data["redirect_uri"]  = "http://www.padisetty.com";
                data["grant_type"]    = "authorization_code";

                var response = wc.UploadValues(
                    "https://accounts.google.com/o/oauth2/token",
                    "POST", data);

                string responsebody = Encoding.UTF8.GetString(response);

                dynamic result = JsonConvert.DeserializeObject(responsebody);

                id_token = result.id_token;
            }

            AssumeRoleWithWebIdentityRequest assumeRoleWithWebIdentityRequest =
                new AssumeRoleWithWebIdentityRequest()
            {
                WebIdentityToken = id_token,
                RoleArn          = role
            };

            return(GetAssumeRoleWithWebIdentityResponse(assumeRoleWithWebIdentityRequest));
        }
Exemplo n.º 26
0
        public AssumeRoleWithWebIdentityResponse GetTemporaryCredentialUsingGoogle(
            string client_id,
            string role)
        {
            string query = "https://accounts.google.com/o/oauth2/auth?" +
                           string.Format("client_id={0}&", client_id) +
                           "response_type=id_token&" +
                           "scope=email%20profile&" +
                           "redirect_uri=http://www.padisetty.com";

            AssumeRoleWithWebIdentityRequest assumeRoleWithWebIdentityRequest =
                new AssumeRoleWithWebIdentityRequest()
            {
                WebIdentityToken = GetToken("id_token", query),
                RoleArn          = role
            };

            return(GetAssumeRoleWithWebIdentityResponse(
                       assumeRoleWithWebIdentityRequest));
        }
Exemplo n.º 27
0
        /// <summary>
        /// Constructs an GoogleCompatCredentials object.
        /// </summary>
        /// <param name="sourceCredentials">The Google credential that implements Google.Apis.Auth.OAuth2.IOidcTokenProvider.</param>
        /// <param name="targetAudience">The audience value for the GoogleOIDC Token.</param>
        /// <param name="assumeRoleWithWebIdentityRequest">AssumeRoleWithWebIdentityRequest structure that specifies the Arn, SessionName.</param>
        /// <param name="options">Options to be used in the call to AssumeRole. Not implemented!</param>
        public GoogleCompatCredentials(Google.Apis.Auth.OAuth2.IOidcTokenProvider sourceCredentials, string targetAudience, AssumeRoleWithWebIdentityRequest wr, AssumeRoleAWSCredentialsOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            SourceCredentials = sourceCredentials;
            TargetAudience    = defaultTargetAudience;
            if (targetAudience != "")
            {
                TargetAudience = targetAudience;
            }

            TargetAssumeRoleRequest = wr;
            Options = options;
            // Make sure to fetch new credentials well before the current credentials expire to avoid
            // any request being made with expired credentials.
            PreemptExpiryTime = TimeSpan.FromMinutes(5);
        }
Exemplo n.º 28
0
        public AssumeRoleWithWebIdentityResponse GetTemporaryCredentialUsingAmazon(
            string client_id,
            string role)
        {
            string query = "https://www.amazon.com/ap/oa?" +
                           string.Format("client_id={0}&", client_id) +
                           "response_type=token&" +
                           "scope=profile&" +
                           "redirect_uri=https://www.google.com";

            AssumeRoleWithWebIdentityRequest assumeRoleWithWebIdentityRequest =
                new AssumeRoleWithWebIdentityRequest()
            {
                ProviderId       = "www.amazon.com",
                WebIdentityToken = GetToken("access_token", query),
                RoleArn          = role
            };

            return(GetAssumeRoleWithWebIdentityResponse(
                       assumeRoleWithWebIdentityRequest));
        }
Exemplo n.º 29
0
        private static async Task <SessionAWSCredentials> getTemporaryCredentialsAsync(String idToken, String roleArn, String sessionName)
        {
            using (var stsClient = new AmazonSecurityTokenServiceClient())
            {
                var getSessionTokenRequest = new AssumeRoleWithWebIdentityRequest
                {
                    RoleSessionName  = sessionName,
                    RoleArn          = roleArn,
                    WebIdentityToken = idToken
                };

                AssumeRoleWithWebIdentityResponse sessionTokenResponse = await stsClient.AssumeRoleWithWebIdentityAsync(getSessionTokenRequest);

                Credentials credentials = sessionTokenResponse.Credentials;

                var sessionCredentials =
                    new SessionAWSCredentials(credentials.AccessKeyId,
                                              credentials.SecretAccessKey,
                                              credentials.SessionToken);
                return(sessionCredentials);
            }
        }
Exemplo n.º 30
0
        private async System.Threading.Tasks.Task <CredentialsRefreshState> GetCredentialsForRoleAsync(string roleArn)
        {
            CredentialsRefreshState credentialsState;
            // Retrieve Open Id Token
            // (Reuses existing IdentityId or creates a new one)
            var identityId = await GetIdentityIdAsync().ConfigureAwait(false);

            var getTokenRequest = new GetOpenIdTokenRequest {
                IdentityId = identityId
            };

            // If logins are set, pass them to the GetOpenId call
            if (Logins.Count > 0)
            {
                getTokenRequest.Logins = Logins;
            }
            var getTokenResult = await cib.GetOpenIdTokenAsync(getTokenRequest).ConfigureAwait(false);

            string token = getTokenResult.Token;

            // IdentityId may have changed, save the new value
            UpdateIdentity(getTokenResult.IdentityId, true);

            // Assume role with Open Id Token
            var assumeRequest = new AssumeRoleWithWebIdentityRequest
            {
                WebIdentityToken = token,
                RoleArn          = roleArn,
                RoleSessionName  = "NetProviderSession",
                DurationSeconds  = DefaultDurationSeconds
            };
            var credentials = (await sts.AssumeRoleWithWebIdentityAsync(assumeRequest).ConfigureAwait(false)).Credentials;

            // Return new refresh state (credentials and expiration)
            credentialsState = new CredentialsRefreshState(credentials.GetCredentials(), credentials.Expiration);
            return(credentialsState);
        }