private static void UnmarshallResult(XmlUnmarshallerContext context, GetSessionTokenResponse response)
        {
            int originalDepth = context.CurrentDepth;
            int targetDepth   = originalDepth + 1;

            if (context.IsStartOfDocument)
            {
                targetDepth += 2;
            }

            while (context.ReadAtDepth(originalDepth))
            {
                if (context.IsStartElement || context.IsAttribute)
                {
                    if (context.TestExpression("Credentials", targetDepth))
                    {
                        var unmarshaller = CredentialsUnmarshaller.Instance;
                        response.Credentials = unmarshaller.Unmarshall(context);
                        continue;
                    }
                }
            }

            return;
        }
Пример #2
0
        private void BasicStsSample()
        {
            {
                #region Sample 1

                GetSessionTokenResponse response    = Client.GetSessionToken();
                Credentials             credentials = response.Credentials;
                Console.WriteLine("Access Key = {0}", credentials.AccessKeyId);
                Console.WriteLine("Secret Key = {0}", credentials.SecretAccessKey);
                Console.WriteLine("Session Token = {0}", credentials.SessionToken);
                Console.WriteLine("Expiration = {0}", credentials.Expiration);

                #endregion
            }
            {
                #region Sample 2

                GetSessionTokenResponse response = Client.GetSessionToken(new GetSessionTokenRequest
                {
                    DurationSeconds = (int)TimeSpan.FromHours(8).TotalSeconds
                });
                Credentials credentials = response.Credentials;
                Console.WriteLine("Access Key = {0}", credentials.AccessKeyId);
                Console.WriteLine("Secret Key = {0}", credentials.SecretAccessKey);
                Console.WriteLine("Session Token = {0}", credentials.SessionToken);
                Console.WriteLine("Expiration = {0}", credentials.Expiration);

                #endregion
            }
        }
Пример #3
0
        public TemporaryUploadCredentials GenerateTemporaryUploadCredentials()
        {
            return(base.ExecuteFunction("GenerateTemporaryUploadCredentials", delegate()
            {
                Credentials credentials = this.Cache15.PerLifetime("GetSessionToken", delegate()
                {
                    // Cache is every 15 minutes, we set the expire every 30, we're good. :)

                    using (var client = new AmazonSecurityTokenServiceClient(this.AmazonKeyID, this.AmazonSecret, RegionEndpoint.USEast1))
                    {
                        GetSessionTokenResponse response = client.GetSessionToken(new GetSessionTokenRequest
                        {
                            DurationSeconds = (int)TimeSpan.FromMinutes(30).TotalSeconds,
                        });

                        if (response == null || response.HttpStatusCode != System.Net.HttpStatusCode.OK || response.Credentials == null)
                        {
                            throw new UIException("Unable to generate File Upload Credentials. Please try again in a few moments");
                        }
                        return response.Credentials;
                    }
                });

                return new TemporaryUploadCredentials()
                {
                    bucket = this.AmazonBucket,
                    access_key_id = credentials.AccessKeyId,
                    secret_access_key = credentials.SecretAccessKey,
                    session_token = credentials.SessionToken,
                };
            }));
        }
Пример #4
0
        private AWSCredentials GetSessionCredentials(AWSCredentials credentials)
        {
            using (var stsClient = new AmazonSecurityTokenServiceClient(credentials))
            {
                GetSessionTokenResponse response = null;

                // wait for eventual consistency of user creation
                UtilityMethods.WaitUntil(() =>
                {
                    try
                    {
                        response = stsClient.GetSessionToken();
                        return(true);
                    }
                    catch (AmazonSecurityTokenServiceException e)
                    {
                        if (String.Equals(e.ErrorCode, "InvalidClientTokenId", StringComparison.OrdinalIgnoreCase))
                        {
                            return(false);
                        }
                        else
                        {
                            throw e;
                        }
                    }
                });

                Assert.IsNotNull(response);
                Assert.IsNotNull(response.Credentials);

                return(new SessionAWSCredentials(response.Credentials.AccessKeyId,
                                                 response.Credentials.SecretAccessKey, response.Credentials.SessionToken));
            }
        }
Пример #5
0
        public void TestGetSessionTokenAsync()
        {
            var gstRequest = new GetSessionTokenRequest()
            {
                DurationSeconds = 3600
            };

            GetSessionTokenResponse asyncResponse = null;

            var task = Client.GetSessionTokenAsync(gstRequest);

            asyncResponse = task.Result;

            UtilityMethods.Sleep(TimeSpan.FromSeconds(5));
            Assert.IsNotNull(asyncResponse);

            var gstResult = asyncResponse;

            Assert.IsNotNull(gstResult);
            Assert.IsNotNull(gstResult.Credentials.AccessKeyId);
            Assert.IsNotNull(gstResult.Credentials.SecretAccessKey);
            Assert.IsNotNull(gstResult.Credentials.SessionToken);
            Assert.IsNotNull(gstResult.Credentials.Expiration);

            var time = DateTime.Now;
            var approximateExpires = time.AddHours(1);
            var expiresAfter       = approximateExpires.AddMinutes(-5);
            var expiresBefore      = approximateExpires.AddMinutes(5);
            var expires            = gstResult.Credentials.Expiration;

            Assert.IsTrue(expires > expiresAfter);
            Assert.IsTrue(expires < expiresBefore);
        }
Пример #6
0
        /// <summary>
        /// </summary>
        ///
        /// <param name="getSessionTokenRequest">Container for the necessary parameters to execute the GetSessionToken service method on
        ///           AmazonSecurityTokenService.</param>
        ///
        /// <returns>The response from the GetSessionToken service method, as returned by AmazonSecurityTokenService.</returns>
        ///
        public GetSessionTokenResponse GetSessionToken(GetSessionTokenRequest getSessionTokenRequest)
        {
            IRequest <GetSessionTokenRequest> request  = new GetSessionTokenRequestMarshaller().Marshall(getSessionTokenRequest);
            GetSessionTokenResponse           response = Invoke <GetSessionTokenRequest, GetSessionTokenResponse> (request, this.signer, GetSessionTokenResponseUnmarshaller.GetInstance());

            return(response);
        }
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            GetSessionTokenResponse response = new GetSessionTokenResponse();

            context.Read();
            int targetDepth = context.CurrentDepth;

            while (context.ReadAtDepth(targetDepth))
            {
                if (context.IsStartElement)
                {
                    if (context.TestExpression("GetSessionTokenResult", 2))
                    {
                        UnmarshallResult(context, response);
                        continue;
                    }

                    if (context.TestExpression("ResponseMetadata", 2))
                    {
                        response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context);
                    }
                }
            }

            return(response);
        }
Пример #8
0
        public Credentials GetSessionToken(AWSCredentials credentials)
        {
            Credentials sessionCredentials = null;

            using (var stsClient = new AmazonSecurityTokenServiceClient(credentials))
            {
                try
                {
                    var getSessionTokenRequest = new GetSessionTokenRequest()
                    {
                        DurationSeconds = 7200
                    };

                    GetSessionTokenResponse response = stsClient.GetSessionToken(getSessionTokenRequest);

                    sessionCredentials = response.Credentials;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            return(sessionCredentials);
        }
Пример #9
0
        private async Task <Credentials> GetTemporaryCredentials(
            string accessKeyId, string secretAccessKeyId)
        {
            AmazonSecurityTokenServiceClient stsClient =
                new AmazonSecurityTokenServiceClient(accessKeyId,
                                                     secretAccessKeyId);

            GetSessionTokenRequest getSessionTokenRequest =
                new GetSessionTokenRequest();

            getSessionTokenRequest.DurationSeconds = 7200; // seconds

            GetSessionTokenResponse sessionTokenResponse =
                await stsClient.GetSessionTokenAsync(getSessionTokenRequest);

            Credentials credentials = sessionTokenResponse.Credentials;

            //SessionAWSCredentials sessionCredentials =
            //    new SessionAWSCredentials(credentials.AccessKeyId,
            //                              credentials.SecretAccessKey,
            //                              credentials.SessionToken);


            return(credentials);
        }
        private async Task EC2Instance(AssetScanCompletedEvent request)
        {
            IAmazonSecurityTokenService STSClient = new AmazonSecurityTokenServiceClient("AKIAXMJHA33LOQPJKCXO", "t1EvatLh4zIl7cBNyGR8rEE2k1vgKOiiDu6wg8IT", RegionEndpoint.USEast2);

            using (var client = STSClient)
            {
                GetSessionTokenRequest getSessionTokenRequest = new GetSessionTokenRequest()
                {
                    DurationSeconds = 900
                };
                GetSessionTokenResponse tokenResponse = await client.GetSessionTokenAsync(getSessionTokenRequest);

                //Console.WriteLine("SecretAccessKey: "+tokenResponse.Credentials.SecretAccessKey+" \n  AccessKeyId: "+tokenResponse.Credentials.AccessKeyId+"\n SessionToken: "+tokenResponse.Credentials.SessionToken+" \n Expiration: "+tokenResponse.Credentials.Expiration);

                var response = STSClient.AssumeRoleAsync(new AssumeRoleRequest
                {
                    RoleArn         = "arn:aws:iam::507424857814:role/DemoEC2",
                    RoleSessionName = "EC2User",
                    DurationSeconds = 900
                });

                var tempCredentials = new SessionAWSCredentials
                                      (
                    response.Result.Credentials.AccessKeyId,
                    response.Result.Credentials.SecretAccessKey,
                    response.Result.Credentials.SessionToken
                                      );
                // var test= new BasicAWSCredentials("AKIAXMJHA33LOQPJKCXO","t1EvatLh4zIl7cBNyGR8rEE2k1vgKOiiDu6wg8IT");
                //Console.WriteLine("SecretAccessKey: " + response.Result.Credentials.SecretAccessKey + " \n AccessKey: " + response.Result.Credentials.AccessKeyId + " \n SessionToken: " + response.Result.Credentials.SessionToken + " \n Expiration: " + response.Result.Credentials.Expiration);
                //await Task.Delay(900500);
                //Console.WriteLine("Afetr 15 minute .......");

                IAmazonEC2 ec2 = new AmazonEC2Client(tempCredentials, Amazon.RegionEndpoint.USEast2);
                //Amazon.Util.EC2InstanceMetadata.Hostname;

                // list of Instance
                var result = await ec2.DescribeInstancesAsync();

                // Console.WriteLine("\n List of Instance");
                foreach (var reservation in result.Reservations)
                {
                    foreach (var instance in reservation.Instances)
                    {
                        _logger.LogInformation("EC2 for instance ID {0} {1} {2}", request.ScanID, instance.InstanceId, instance.InstanceType);
                        //Console.WriteLine(instance.InstanceId);
                    }
                }
                //Console.WriteLine("\n Get by InstanceID");
                //var response2 = ec2.DescribeInstancesAsync(new DescribeInstancesRequest
                //{
                //    InstanceIds = new List<string>
                //    {
                //        "i-0e76148b03298009a"
                //    }
                //});

                //Console.WriteLine(response2.Result.HttpStatusCode);
            }
        }
        private static void UnmarshallResult(XmlUnmarshallerContext context, GetSessionTokenResponse response)
        {
            int currentDepth = context.get_CurrentDepth();
            int num          = currentDepth + 1;

            if (context.get_IsStartOfDocument())
            {
                num += 2;
            }
            while (context.ReadAtDepth(currentDepth))
            {
                if ((context.get_IsStartElement() || context.get_IsAttribute()) && context.TestExpression("Credentials", num))
                {
                    CredentialsUnmarshaller instance = CredentialsUnmarshaller.Instance;
                    response.Credentials = instance.Unmarshall(context);
                }
            }
        }
Пример #12
0
        public void TestGetSessionTokenAsync()
        {
            var gstRequest = new GetSessionTokenRequest()
            {
                DurationSeconds = 3600
            };

            GetSessionTokenResponse asyncResponse = null;

#if ASYNC_AWAIT
            var task = Client.GetSessionTokenAsync(gstRequest);
            asyncResponse = task.Result;
#else
            var asyncResult = Client.BeginGetSessionToken(gstRequest,
                                                          ar =>
            {
                var client    = ar.AsyncState as AmazonSecurityTokenServiceClient;
                asyncResponse = client.EndGetSessionToken(ar);
            }
                                                          , Client);
            asyncResult.AsyncWaitHandle.WaitOne();
#endif

            Thread.Sleep(TimeSpan.FromSeconds(5));
            Assert.IsNotNull(asyncResponse);

            var gstResult = asyncResponse;
            Assert.IsNotNull(gstResult);
            Assert.IsNotNull(gstResult.Credentials.AccessKeyId);
            Assert.IsNotNull(gstResult.Credentials.SecretAccessKey);
            Assert.IsNotNull(gstResult.Credentials.SessionToken);
            Assert.IsNotNull(gstResult.Credentials.Expiration);

            var time = DateTime.Now;
            var approximateExpires = time.AddHours(1);
            var expiresAfter       = approximateExpires.AddMinutes(-5);
            var expiresBefore      = approximateExpires.AddMinutes(5);
            var expires            = gstResult.Credentials.Expiration;

            Assert.IsTrue(expires > expiresAfter);
            Assert.IsTrue(expires < expiresBefore);
        }
Пример #13
0
        private static async Task <SessionAWSCredentials> GetTemporaryCredentialsAsync()
        {
            using var stsClient = new AmazonSecurityTokenServiceClient();
            var getSessionTokenRequest = new GetSessionTokenRequest
            {
                DurationSeconds = 7200                 // seconds
            };

            GetSessionTokenResponse sessionTokenResponse =
                await stsClient.GetSessionTokenAsync(getSessionTokenRequest);

            Credentials credentials = sessionTokenResponse.Credentials;

            var sessionCredentials =
                new SessionAWSCredentials(credentials.AccessKeyId,
                                          credentials.SecretAccessKey,
                                          credentials.SessionToken);

            return(sessionCredentials);
        }
        private async Task <SessionAWSCredentials> GetTemporaryCredentials()
        {
            AmazonSecurityTokenServiceClient stsClient =
                new AmazonSecurityTokenServiceClient(_options.AwsAccessKey,
                                                     _options.AwsSerectKey);
            GetSessionTokenRequest getSessionTokenRequest = new GetSessionTokenRequest {
                DurationSeconds = 7200
            };
            GetSessionTokenResponse sessionTokenResponse = await
                                                           stsClient.GetSessionTokenAsync(getSessionTokenRequest);

            Credentials credentials = sessionTokenResponse.Credentials;

            SessionAWSCredentials sessionCredential =
                new SessionAWSCredentials(credentials.AccessKeyId,
                                          credentials.SecretAccessKey,
                                          credentials.SessionToken);

            return(sessionCredential);
        }
Пример #15
0
        /// <summary>
        /// https://docs.aws.amazon.com/AmazonS3/latest/dev/AuthUsingTempSessionTokenDotNet.html
        /// </summary>
        /// <returns></returns>
        private static async Task <Credentials> GetTemporaryCredentialsAsync()
        {
            var awsCredentials = GetAwsCredentials();

            using (var stsClient = new AmazonSecurityTokenServiceClient(awsCredentials))
            {
                var getSessionTokenRequest = new GetSessionTokenRequest
                {
                    DurationSeconds = 7200 // seconds
                };

                Log.LogInformation($"GetSessionToken from AWS with a lifetime of {getSessionTokenRequest.DurationSeconds}s");
                GetSessionTokenResponse sessionTokenResponse = await stsClient.GetSessionTokenAsync(getSessionTokenRequest);

                Credentials credentials = sessionTokenResponse.Credentials;
                Log.LogInformation($"Got Session Token: AccessKeyId {credentials.AccessKeyId}'");
                // Log.LogInformation($"Got Session Token: AccessKeyId {credentials.AccessKeyId}', SecretAccessKey'{credentials.SecretAccessKey}', SessionToken '{credentials.SessionToken}'");

                return(credentials);
            }
        }
Пример #16
0
        private void GetSessionToken()
        {
            Dictionary <string, string> args = new Dictionary <string, string>();

            args.Add("email", user);
            args.Add("password", pasw);
            args.Add("application_id", appId);
            args.Add("token_version", "2");
            args.Add("response_format", "json");
            args.Add("signature", GetInitSignature());
            string respStr = SendRequestMultiPart(apiUrl + "user/get_session_token.php", args);
            GetSessionTokenResponse resp = DeserializeResponse <GetSessionTokenResponse>(respStr);

            EnsureSuccess(resp);
            if (resp.session_token == null || resp.time == null || resp.secret_key == null)
            {
                throw new IOException("Invalid response");
            }
            sessionToken  = resp.session_token;
            signatureTime = resp.time;
            signatureKey  = (int)resp.secret_key;
        }
Пример #17
0
        private async Task <CredentialModel> GetBjjCredentials()
        {
            using (var stsClient = new AmazonSecurityTokenServiceClient())
            {
                var getSessionTokenRequest = new GetSessionTokenRequest
                {
                    DurationSeconds = 7200 // seconds
                };

                GetSessionTokenResponse sessionTokenResponse =
                    await stsClient.GetSessionTokenAsync(getSessionTokenRequest);

                Credentials credentials = sessionTokenResponse.Credentials;

                return(new CredentialModel
                {
                    Key = credentials.AccessKeyId,
                    Secret = credentials.SecretAccessKey,
                    Token = credentials.SessionToken
                });
            }
        }
Пример #18
0
        public void TestGetSessionTokenAsync()
        {
            var gstRequest = new GetSessionTokenRequest()
            {
                DurationSeconds = 3600
            };


            GetSessionTokenResponse gstResult = null;
            AutoResetEvent          ars       = new AutoResetEvent(false);

            Client.GetSessionTokenAsync(gstRequest, (result) =>
            {
                gstResult = result.Response;
                ars.Set();
            }, new Amazon.Runtime.AsyncOptions()
            {
                ExecuteCallbackOnMainThread = false
            });

            ars.WaitOne();

            Thread.Sleep(TimeSpan.FromSeconds(5));
            Assert.IsNotNull(gstResult);
            Assert.IsNotNull(gstResult.Credentials.AccessKeyId);
            Assert.IsNotNull(gstResult.Credentials.SecretAccessKey);
            Assert.IsNotNull(gstResult.Credentials.SessionToken);
            Assert.IsNotNull(gstResult.Credentials.Expiration);

            var time = DateTime.Now;
            var approximateExpires = time.AddHours(1);
            var expiresAfter       = approximateExpires.AddMinutes(-5);
            var expiresBefore      = approximateExpires.AddMinutes(5);
            var expires            = gstResult.Credentials.Expiration;

            Utils.AssertTrue(expires > expiresAfter);
            Utils.AssertTrue(expires < expiresBefore);
        }
Пример #19
0
        public void TestGetSessionTokenRegional()
        {
            using (var uswest2Client = TestBase.CreateClient <AmazonSecurityTokenServiceClient>(endpoint: RegionEndpoint.USWest2))
            {
                var gstRequest = new GetSessionTokenRequest()
                {
                    DurationSeconds = 3600
                };

                GetSessionTokenResponse gstResult = null;
                AutoResetEvent          ars       = new AutoResetEvent(false);
                uswest2Client.GetSessionTokenAsync(gstRequest, (result) =>
                {
                    gstResult = result.Response;
                    ars.Set();
                }, new Amazon.Runtime.AsyncOptions()
                {
                    ExecuteCallbackOnMainThread = false
                });

                ars.WaitOne();

                Assert.IsNotNull(gstResult);
                Assert.IsNotNull(gstResult.Credentials.AccessKeyId);
                Assert.IsNotNull(gstResult.Credentials.SecretAccessKey);
                Assert.IsNotNull(gstResult.Credentials.SessionToken);
                Assert.IsNotNull(gstResult.Credentials.Expiration);

                var time = DateTime.Now;
                var approximateExpires = time.AddHours(1);
                var expiresAfter       = approximateExpires.AddMinutes(-5);
                var expiresBefore      = approximateExpires.AddMinutes(5);
                var expires            = gstResult.Credentials.Expiration;

                Utils.AssertTrue(expires > expiresAfter);
                Utils.AssertTrue(expires < expiresBefore);
            }
        }
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            GetSessionTokenResponse response = new GetSessionTokenResponse();

            while (context.Read())
            {
                if (context.IsStartElement)
                {
                    if (context.TestExpression("GetSessionTokenResult", 2))
                    {
                        response.GetSessionTokenResult = GetSessionTokenResultUnmarshaller.GetInstance().Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("ResponseMetadata", 2))
                    {
                        response.ResponseMetadata = ResponseMetadataUnmarshaller.GetInstance().Unmarshall(context);
                    }
                }
            }


            return(response);
        }
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            GetSessionTokenResponse getSessionTokenResponse = new GetSessionTokenResponse();

            context.Read();
            int currentDepth = context.get_CurrentDepth();

            while (context.ReadAtDepth(currentDepth))
            {
                if (context.get_IsStartElement())
                {
                    if (context.TestExpression("GetSessionTokenResult", 2))
                    {
                        UnmarshallResult(context, getSessionTokenResponse);
                    }
                    else if (context.TestExpression("ResponseMetadata", 2))
                    {
                        getSessionTokenResponse.set_ResponseMetadata(ResponseMetadataUnmarshaller.get_Instance().Unmarshall(context));
                    }
                }
            }
            return(getSessionTokenResponse);
        }
Пример #22
0
        public string Index(string httpMethod, string path, string queries, string headers, string policy, string sts, string callback)
        {
            string ak = "<your ak>";
            string sk = "<your sk>";
            BceClientConfiguration config = new BceClientConfiguration()
            {
                Credentials = new DefaultBceCredentials(ak, sk)
            };

            string result = null;

            if (sts != null)
            {
                StsClient client               = new StsClient(config);
                string    accessControlList    = sts;
                GetSessionTokenRequest request = new GetSessionTokenRequest()
                {
                    DurationSeconds   = 60 * 60 * 24,
                    AccessControlList = accessControlList
                };
                GetSessionTokenResponse response = client.GetSessionToken(request);
                result = JsonConvert.SerializeObject(response);
            }
            else if (policy != null)
            {
                string base64    = Convert.ToBase64String(Encoding.UTF8.GetBytes(policy));
                var    hash      = new HMACSHA256(Encoding.UTF8.GetBytes(sk));
                string signature = EncodeHex(hash.ComputeHash(Encoding.UTF8.GetBytes(base64)));
                result = JsonConvert.SerializeObject(new PolicySignatureResult()
                {
                    policy    = base64,
                    signature = signature,
                    accessKey = ak,
                });
            }
            else
            {
                InternalRequest internalRequest = new InternalRequest();
                internalRequest.Config     = config;
                internalRequest.Uri        = new Uri("http://www.baidu.com" + path);
                internalRequest.HttpMethod = httpMethod;
                if (headers != null)
                {
                    internalRequest.Headers = JsonConvert.DeserializeObject <Dictionary <string, string> > (headers);
                }
                if (queries != null)
                {
                    internalRequest.Parameters = JsonConvert.DeserializeObject <Dictionary <string, string> > (queries);
                }

                BceV1Signer bceV1Signer = new BceV1Signer();
                string      sign        = bceV1Signer.Sign(internalRequest);

                string xbceDate = DateUtils.FormatAlternateIso8601Date(DateTime.Now);
                result = JsonConvert.SerializeObject(new SignatureResult()
                {
                    statusCode = 200,
                    signature  = sign,
                    xbceDate   = xbceDate,
                });
            }

            if (callback != null)
            {
                result = callback + "(" + result + ")";
            }

            return(result);
        }