private static void UnmarshallResult(XmlUnmarshallerContext context, GetFederationTokenResponse 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())
                {
                    if (context.TestExpression("Credentials", num))
                    {
                        CredentialsUnmarshaller instance = CredentialsUnmarshaller.Instance;
                        response.Credentials = instance.Unmarshall(context);
                    }
                    else if (context.TestExpression("FederatedUser", num))
                    {
                        FederatedUserUnmarshaller instance2 = FederatedUserUnmarshaller.Instance;
                        response.FederatedUser = instance2.Unmarshall(context);
                    }
                    else if (context.TestExpression("PackedPolicySize", num))
                    {
                        IntUnmarshaller instance3 = IntUnmarshaller.get_Instance();
                        response.PackedPolicySize = instance3.Unmarshall(context);
                    }
                }
            }
        }
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            GetFederationTokenResponse response = new GetFederationTokenResponse();

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

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

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

            return(response);
        }
Esempio n. 3
0
        private static void GetFederationToken(String User, int Duration = -1)
        {
            AmazonSecurityTokenServiceClient stsClient;

            if (String.IsNullOrEmpty(Token))
            {
                stsClient = new AmazonSecurityTokenServiceClient(AccessKeyId, SecretKey, stsconfig);
            }
            else
            {
                stsClient = new AmazonSecurityTokenServiceClient(AccessKeyId, SecretKey, Token, stsconfig);
            }

            GetFederationTokenRequest federationTokenRequest = new GetFederationTokenRequest();

            if (!String.IsNullOrEmpty(User))
            {
                federationTokenRequest.Name = User;
            }

            if (Duration != -1)
            {
                federationTokenRequest.DurationSeconds = Duration;
            }

            GetFederationTokenResponse federationTokenResponse = stsClient.GetFederationToken(federationTokenRequest);

            Console.WriteLine("Acess key id: {0}", federationTokenResponse.Credentials.AccessKeyId);
            Console.WriteLine("Secret key: {0}", federationTokenResponse.Credentials.SecretAccessKey);
            Console.WriteLine("Session token: {0}", federationTokenResponse.Credentials.SessionToken);
            Console.WriteLine("Expiration: {0}", federationTokenResponse.Credentials.Expiration);
        }
Esempio n. 4
0
        /// <summary>
        /// </summary>
        ///
        /// <param name="getFederationTokenRequest">Container for the necessary parameters to execute the GetFederationToken service method on
        ///           AmazonSecurityTokenService.</param>
        ///
        /// <returns>The response from the GetFederationToken service method, as returned by AmazonSecurityTokenService.</returns>
        ///
        /// <exception cref="PackedPolicyTooLargeException"/>
        /// <exception cref="MalformedPolicyDocumentException"/>
        public GetFederationTokenResponse GetFederationToken(GetFederationTokenRequest getFederationTokenRequest)
        {
            IRequest <GetFederationTokenRequest> request  = new GetFederationTokenRequestMarshaller().Marshall(getFederationTokenRequest);
            GetFederationTokenResponse           response = Invoke <GetFederationTokenRequest, GetFederationTokenResponse> (request, this.signer, GetFederationTokenResponseUnmarshaller.GetInstance());

            return(response);
        }
        public static async Task <SessionAWSCredentials> GetTemporaryFederatedCredentialsAsync(string bucketName)
        {
            var config    = new AmazonSecurityTokenServiceConfig();
            var stsClient = new AmazonSecurityTokenServiceClient(config);

            var federationTokenRequest = new GetFederationTokenRequest();

            federationTokenRequest.DurationSeconds = 7200;
            federationTokenRequest.Name            = "User1";
            federationTokenRequest.Policy          = @"{
               ""Statement"":
               [
                 {
                   ""Sid"":""Stmt1311212314284"",
                   ""Action"":[""s3:ListBucket""],
                   ""Effect"":""Allow"",
                   ""Resource"":""arn:aws:s3:::" + bucketName + @"""
                  }
               ]
             }
            ";

            GetFederationTokenResponse federationTokenResponse =
                await stsClient.GetFederationTokenAsync(federationTokenRequest);

            Credentials credentials = federationTokenResponse.Credentials;

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

            return(sessionCredentials);
        }
Esempio n. 6
0
        public void TestGetFederationTokenAsync()
        {
            var gftRequest = new GetFederationTokenRequest
            {
                Policy          = @"{""Statement"":[{""Effect"":""Allow"",""Action"":""*"",""Resource"":""*""}]}",
                Name            = "BillyBob",
                DurationSeconds = 3600
            };

            GetFederationTokenResponse asyncResponse = null;

#if ASYNC_AWAIT
            var task = Client.GetFederationTokenAsync(gftRequest);
            asyncResponse = task.Result;
#else
            var asyncResult = Client.BeginGetFederationToken(gftRequest,
                                                             ar =>
            {
                var client    = ar.AsyncState as AmazonSecurityTokenServiceClient;
                asyncResponse = client.EndGetFederationToken(ar);
            }
                                                             , Client);
            asyncResult.AsyncWaitHandle.WaitOne();
#endif

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

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

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

            Assert.IsTrue(expires > expiresAfter);
            Assert.IsTrue(expires < expiresBefore);

            Assert.IsNotNull(gftResult.FederatedUser.FederatedUserId);
            Assert.IsNotNull(gftResult.FederatedUser.Arn);

            Assert.IsTrue(gftResult.FederatedUser.FederatedUserId.EndsWith(gftRequest.Name, StringComparison.OrdinalIgnoreCase));
            Assert.IsTrue(gftResult.FederatedUser.Arn.EndsWith(gftRequest.Name, StringComparison.OrdinalIgnoreCase));
        }
Esempio n. 7
0
    public static TemporaryAWSCredentials GetSecurityToken(string userName)
    {
        TemporaryAWSCredentials temporaryCreds = new TemporaryAWSCredentials();
        Credentials             sessionCredentials;

        // Create a client using the credentials from the Web.config file
        AmazonSecurityTokenServiceConfig config = new AmazonSecurityTokenServiceConfig();
        AmazonSecurityTokenServiceClient client = new AmazonSecurityTokenServiceClient(
            GetAccesskey(),
            GetSecretkey(),
            config);

        // Build the aws username
        string awsUsername = BuildAWSUsername(userName);

        // Map policy based on whether this is an internal or external user.
        string policy = BuildAWSPolicy(UserType.Internal);

        // Store the attributes and request a new
        // Federated session(temporary security creds)
        GetFederationTokenRequest request = new GetFederationTokenRequest
        {
            DurationSeconds = 3600 * SESSION_DURATION,
            Name            = awsUsername,
            Policy          = policy
        };

        GetFederationTokenResponse startSessionResponse = null;

        startSessionResponse = client.GetFederationToken(request);

        // Check the result returned i.e. Valid security credentials or null?
        if (startSessionResponse != null)
        {
            GetFederationTokenResult startSessionResult = startSessionResponse.GetFederationTokenResult;
            sessionCredentials = startSessionResult.Credentials;
            // Store all the returned keys and token to TemporarySecurityCreds object.
            temporaryCreds.User            = userName;
            temporaryCreds.AccessKeyId     = sessionCredentials.AccessKeyId;
            temporaryCreds.SecretAccessKey = sessionCredentials.SecretAccessKey;
            temporaryCreds.Expiration      = sessionCredentials.Expiration;
            temporaryCreds.Token           = sessionCredentials.SessionToken;
            return(temporaryCreds);
        }
        else
        {
            throw new Exception("Error in retrieving AWS temporary security creds,recieved NULL");
        }
    }
Esempio n. 8
0
        public void TestGetFederationTokenAsync()
        {
            var gftRequest = new GetFederationTokenRequest
            {
                Policy          = @"{""Statement"":[{""Effect"":""Allow"",""Action"":""*"",""Resource"":""*""}]}",
                Name            = "BillyBob",
                DurationSeconds = 3600
            };

            GetFederationTokenResponse gftResult = null;
            AutoResetEvent             ars       = new AutoResetEvent(false);

            Client.GetFederationTokenAsync(gftRequest, (result) =>
            {
                gftResult = result.Response;
                ars.Set();
            }, options);

            ars.WaitOne();

            Thread.Sleep(TimeSpan.FromSeconds(5));

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

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

            Utils.AssertTrue(expires > expiresAfter);
            Utils.AssertTrue(expires < expiresBefore);

            Assert.IsNotNull(gftResult.FederatedUser.FederatedUserId);
            Assert.IsNotNull(gftResult.FederatedUser.Arn);

            Utils.AssertTrue(gftResult.FederatedUser.FederatedUserId.EndsWith(gftRequest.Name, StringComparison.OrdinalIgnoreCase));
            Utils.AssertTrue(gftResult.FederatedUser.Arn.EndsWith(gftRequest.Name, StringComparison.OrdinalIgnoreCase));
        }
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            GetFederationTokenResponse response = new GetFederationTokenResponse();

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

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

            return(response);
        }
Esempio n. 10
0
        private static void UnmarshallResult(XmlUnmarshallerContext context, GetFederationTokenResponse response)
        {
            int originalDepth = context.CurrentDepth;
            int targetDepth   = originalDepth + 1;

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

            while (context.Read())
            {
                if (context.IsStartElement || context.IsAttribute)
                {
                    if (context.TestExpression("Credentials", targetDepth))
                    {
                        response.Credentials = CredentialsUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                    if (context.TestExpression("FederatedUser", targetDepth))
                    {
                        response.FederatedUser = FederatedUserUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                    if (context.TestExpression("PackedPolicySize", targetDepth))
                    {
                        response.PackedPolicySize = IntUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                }
                else if (context.IsEndElement && context.CurrentDepth < originalDepth)
                {
                    return;
                }
            }



            return;
        }
Esempio n. 11
0
        public void TestGetFederationTokenAsync()
        {
            var gftRequest = new GetFederationTokenRequest
            {
                Policy          = @"{""Statement"":[{""Effect"":""Allow"",""Action"":""*"",""Resource"":""*""}]}",
                Name            = "BillyBob",
                DurationSeconds = 3600
            };

            GetFederationTokenResponse asyncResponse = null;

            var task = Client.GetFederationTokenAsync(gftRequest);

            asyncResponse = task.Result;

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

            var gftResult = asyncResponse;

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

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

            Assert.IsTrue(expires > expiresAfter);
            Assert.IsTrue(expires < expiresBefore);

            Assert.IsNotNull(gftResult.FederatedUser.FederatedUserId);
            Assert.IsNotNull(gftResult.FederatedUser.Arn);

            Assert.IsTrue(gftResult.FederatedUser.FederatedUserId.EndsWith(gftRequest.Name, StringComparison.OrdinalIgnoreCase));
            Assert.IsTrue(gftResult.FederatedUser.Arn.EndsWith(gftRequest.Name, StringComparison.OrdinalIgnoreCase));
        }
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            GetFederationTokenResponse response = new GetFederationTokenResponse();

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


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

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

            while (context.ReadAtDepth(currentDepth))
            {
                if (context.get_IsStartElement())
                {
                    if (context.TestExpression("GetFederationTokenResult", 2))
                    {
                        UnmarshallResult(context, getFederationTokenResponse);
                    }
                    else if (context.TestExpression("ResponseMetadata", 2))
                    {
                        getFederationTokenResponse.set_ResponseMetadata(ResponseMetadataUnmarshaller.get_Instance().Unmarshall(context));
                    }
                }
            }
            return(getFederationTokenResponse);
        }
Esempio n. 14
0
        public static string genCredential(Dictionary <string, object> values)
        {
            Credential cred = new Credential {
                SecretId  = (string)values["secretId"],
                SecretKey = (string)values["secretKey"]
            };

            ClientProfile clientProfile = new ClientProfile();
            HttpProfile   httpProfile   = new HttpProfile();

            httpProfile.Endpoint      = ("sts.tencentcloudapi.com");
            clientProfile.HttpProfile = httpProfile;

            string region      = (string)values["region"];
            string bucket      = (string)values["bucket"];
            string allowPrefix = (string)values["allowPrefix"];

            string[] allowActions = (string[])values["allowActions"];
            string   policy       = getPolicy(region, bucket, allowPrefix, allowActions);

            Dictionary <string, object> body = new Dictionary <string, object>();

            body.Add("DurationSeconds", (Int32)values["durationSeconds"]);
            body.Add("Name", "cos-sts-sdk-dotnet");
            body.Add("Policy", policy);

            StsClient client = new StsClient(cred, region, clientProfile);
            GetFederationTokenRequest req = new GetFederationTokenRequest();

            string strParams = JsonConvert.SerializeObject(body);

            req = GetFederationTokenRequest.FromJsonString <GetFederationTokenRequest>(strParams);
            GetFederationTokenResponse resp = client.GetFederationToken(req).
                                              ConfigureAwait(false).GetAwaiter().GetResult();

            return(JsonConvert.SerializeObject(resp));
        }
Esempio n. 15
0
        /// <summary>
        /// 获取联合身份临时访问凭证
        /// </summary>
        /// <returns></returns>
        public GetFederationTokenResponse GetFederationToken()
        {
            Credential cred = new Credential {
                SecretId  = _cosConfig.SecretId,
                SecretKey = _cosConfig.SecretKey
            };

            ClientProfile clientProfile = new ClientProfile();
            HttpProfile   httpProfile   = new HttpProfile();

            httpProfile.Endpoint      = _cosConfig.EndPoint;
            clientProfile.HttpProfile = httpProfile;

            StsClient client = new StsClient(cred, _cosConfig.Region, clientProfile);
            GetFederationTokenRequest req = new GetFederationTokenRequest();

            req.Name            = _cosConfig.Name;
            req.Policy          = HttpUtility.UrlEncode(_cosConfig.Policy);
            req.DurationSeconds = _cosConfig.DurationSeconds;

            GetFederationTokenResponse resp = client.GetFederationTokenSync(req);

            return(resp);
        }
Esempio n. 16
0
        public static Dictionary <string, object> genCredential(Dictionary <string, object> values)
        {
            checkArguments(values, new string[] { "secretId", "secretKey", "region" });

            Credential cred = new Credential {
                SecretId  = (string)values["secretId"],
                SecretKey = (string)values["secretKey"]
            };
            string region = (string)values["region"];

            ClientProfile clientProfile = new ClientProfile();
            HttpProfile   httpProfile   = new HttpProfile();
            String        endpoint      = values.ContainsKey("Domain") ? (string)values["Domain"]:
                                          "sts.tencentcloudapi.com";

            httpProfile.Endpoint      = endpoint;
            clientProfile.HttpProfile = httpProfile;

            // get policy
            string policy = null;

            if (values.ContainsKey("policy"))
            {
                policy = (string)values["policy"];
            }
            if (policy == null)
            {
                checkArguments(values, new string[] { "bucket", "allowActions" });
                string   bucket       = (string)values["bucket"];
                string[] allowActions = (string[])values["allowActions"];
                string[] allowPrefixes;
                if (values.ContainsKey("allowPrefix"))
                {
                    allowPrefixes = new string[] { (string)values["allowPrefix"] };
                }
                else if (values.ContainsKey("allowPrefixes"))
                {
                    allowPrefixes = (string[])values["allowPrefixes"];
                }
                else
                {
                    throw new System.ArgumentException("allowPrefix and allowPrefixes are both null.");
                }
                policy = getPolicy(region, bucket, allowPrefixes, allowActions);
            }

            // duration
            Int32 durationSeconds = 1800;

            if (values.ContainsKey("durationSeconds"))
            {
                durationSeconds = (Int32)values["durationSeconds"];
            }

            Dictionary <string, object> body = new Dictionary <string, object>();

            body.Add("DurationSeconds", durationSeconds);
            body.Add("Name", "cos-sts-sdk-dotnet");
            body.Add("Policy", policy);

            StsClient client = new StsClient(cred, region, clientProfile);
            GetFederationTokenRequest req = new GetFederationTokenRequest();

            string strParams = JsonConvert.SerializeObject(body);

            req = GetFederationTokenRequest.FromJsonString <GetFederationTokenRequest>(strParams);
            GetFederationTokenResponse resp = client.GetFederationTokenSync(req);
            string jsonString = JsonConvert.SerializeObject(resp);
            Dictionary <string, object> dic = JsonConvert.DeserializeObject <Dictionary <string, object> >(jsonString);

            if (dic.ContainsKey("ExpiredTime"))
            {
                dic.Add("StartTime", Int32.Parse(dic["ExpiredTime"].ToString()) - durationSeconds);
            }
            return(dic);
        }