Пример #1
0
    protected virtual async Task <SessionAWSCredentials> GetTemporaryFederatedCredentialsAsync(
        AwsBlobProviderConfiguration configuration)
    {
        Check.NotNullOrWhiteSpace(configuration.Name, nameof(configuration.Name));
        Check.NotNullOrWhiteSpace(configuration.Policy, nameof(configuration.Policy));

        var temporaryCredentialsCache = await Cache.GetAsync(configuration.TemporaryCredentialsCacheKey);

        if (temporaryCredentialsCache == null)
        {
            AmazonSecurityTokenServiceClient stsClient;

            if (!configuration.AccessKeyId.IsNullOrEmpty() && !configuration.SecretAccessKey.IsNullOrEmpty())
            {
                stsClient = new AmazonSecurityTokenServiceClient(configuration.AccessKeyId,
                                                                 configuration.SecretAccessKey);
            }
            else
            {
                var awsCredentials = GetAwsCredentials(configuration);
                stsClient = awsCredentials == null
                    ? new AmazonSecurityTokenServiceClient()
                    : new AmazonSecurityTokenServiceClient(awsCredentials);
            }

            using (stsClient)
            {
                var federationTokenRequest =
                    new GetFederationTokenRequest
                {
                    DurationSeconds = configuration.DurationSeconds,
                    Name            = configuration.Name,
                    Policy          = configuration.Policy
                };

                var federationTokenResponse =
                    await stsClient.GetFederationTokenAsync(federationTokenRequest);

                var credentials = federationTokenResponse.Credentials;

                temporaryCredentialsCache =
                    await SetTemporaryCredentialsCache(configuration, credentials);
            }
        }

        var sessionCredentials = new SessionAWSCredentials(
            StringEncryptionService.Decrypt(temporaryCredentialsCache.AccessKeyId),
            StringEncryptionService.Decrypt(temporaryCredentialsCache.SecretAccessKey),
            StringEncryptionService.Decrypt(temporaryCredentialsCache.SessionToken));

        return(sessionCredentials);
    }
Пример #2
0
        internal GetFederationTokenResponse GetFederationToken(GetFederationTokenRequest request)
        {
            var task = GetFederationTokenAsync(request);

            try
            {
                return(task.Result);
            }
            catch (AggregateException e)
            {
                ExceptionDispatchInfo.Capture(e.InnerException).Throw();
                return(null);
            }
        }
Пример #3
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));
        }
Пример #4
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");
        }
    }
Пример #5
0
        /// <summary>
        /// Initiates the asynchronous execution of the GetFederationToken operation.
        /// <seealso cref="Amazon.SecurityToken.IAmazonSecurityTokenService"/>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the GetFederationToken operation.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes</param>
        /// <returns>void</returns>
        public void GetFederationTokenAsync(GetFederationTokenRequest 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 GetFederationTokenRequestMarshaller();
                var unmarshaller = GetFederationTokenResponseUnmarshaller.Instance;
                Invoke(request, callback, state, marshaller, unmarshaller, signer);
            }));
            return;
        }
Пример #6
0
        /// <summary>
        /// 获取联合身份临时访问凭证
        /// </summary>
        /// <param name="req"><see cref="GetFederationTokenRequest"/></param>
        /// <returns><see cref="GetFederationTokenResponse"/></returns>
        public GetFederationTokenResponse GetFederationTokenSync(GetFederationTokenRequest req)
        {
            JsonResponseModel <GetFederationTokenResponse> rsp = null;

            try
            {
                var strResp = this.InternalRequestSync(req, "GetFederationToken");
                rsp = JsonConvert.DeserializeObject <JsonResponseModel <GetFederationTokenResponse> >(strResp);
            }
            catch (JsonSerializationException e)
            {
                throw new TencentCloudSDKException(e.Message);
            }
            return(rsp.Response);
        }
        private async Task <string> GetSigninTokenUrl()
        {
            var request = new GetFederationTokenRequest(UserName);

            request.DurationSeconds = SessionDurationSec;
            request.Policy          = Policy;

            var response = await stsClient.GetFederationTokenAsync(request);

            var credential = response.Credentials;

            var json = JsonConvert.SerializeObject(new SessionJson(credential.AccessKeyId, credential.SecretAccessKey, credential.SessionToken));
            var url  = $"{federatedSigninUrl}?Action=getSigninToken&Session={Uri.EscapeDataString(json)}";

            return(url);
        }
Пример #8
0
        /// <summary>
        /// Initiates the asynchronous execution of the GetFederationToken operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the GetFederationToken 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 GetFederationTokenAsync(GetFederationTokenRequest request, AmazonServiceCallback <GetFederationTokenRequest, GetFederationTokenResponse> callback, AsyncOptions options = null)
        {
            options = options == null?new AsyncOptions():options;
            var marshaller   = new GetFederationTokenRequestMarshaller();
            var unmarshaller = GetFederationTokenResponseUnmarshaller.Instance;
            Action <AmazonWebServiceRequest, AmazonWebServiceResponse, Exception, AsyncOptions> callbackHelper = null;

            if (callback != null)
            {
                callbackHelper = (AmazonWebServiceRequest req, AmazonWebServiceResponse res, Exception ex, AsyncOptions ao) => {
                    AmazonServiceResult <GetFederationTokenRequest, GetFederationTokenResponse> responseObject
                        = new AmazonServiceResult <GetFederationTokenRequest, GetFederationTokenResponse>((GetFederationTokenRequest)req, (GetFederationTokenResponse)res, ex, ao.State);
                    callback(responseObject);
                }
            }
            ;
            BeginInvoke <GetFederationTokenRequest>(request, marshaller, unmarshaller, options, callbackHelper);
        }
Пример #9
0
        public void GetFederationTokenAsync(GetFederationTokenRequest request, AmazonServiceCallback <GetFederationTokenRequest, GetFederationTokenResponse> 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));
            GetFederationTokenRequestMarshaller    getFederationTokenRequestMarshaller = new GetFederationTokenRequestMarshaller();
            GetFederationTokenResponseUnmarshaller instance = GetFederationTokenResponseUnmarshaller.Instance;
            Action <AmazonWebServiceRequest, AmazonWebServiceResponse, Exception, AsyncOptions> action = null;

            if (callback != null)
            {
                action = delegate(AmazonWebServiceRequest req, AmazonWebServiceResponse res, Exception ex, AsyncOptions ao)
                {
                    AmazonServiceResult <GetFederationTokenRequest, GetFederationTokenResponse> val = new AmazonServiceResult <GetFederationTokenRequest, GetFederationTokenResponse>((GetFederationTokenRequest)req, (GetFederationTokenResponse)res, ex, ao.get_State());
                    callback.Invoke(val);
                };
            }
            this.BeginInvoke <GetFederationTokenRequest>(request, getFederationTokenRequestMarshaller, instance, options, action);
        }
Пример #10
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));
        }
Пример #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));
        }
Пример #12
0
        private static async Task <SessionAWSCredentials> GetTemporaryFederatedCredentialsAsync()
        {
            AmazonSecurityTokenServiceConfig config    = new AmazonSecurityTokenServiceConfig();
            AmazonSecurityTokenServiceClient stsClient =
                new AmazonSecurityTokenServiceClient(
                    config);

            GetFederationTokenRequest 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;

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

            return(sessionCredentials);
        }
Пример #13
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));
        }
Пример #14
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);
        }
 public Task <GetFederationTokenResponse> GetFederationTokenAsync(GetFederationTokenRequest request,
                                                                  CancellationToken cancellationToken = new CancellationToken())
 {
     throw new System.NotImplementedException();
 }
Пример #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);
        }
Пример #17
0
        /// <summary>
        /// <para>The GetFederationToken action returns a set of temporary credentials for a federated user with the user name and policy specified in
        /// the request. The credentials consist of an Access Key ID, a Secret Access Key, and a security token. Credentials created by IAM users are
        /// valid for the specified duration, between 15 minutes and 36 hours; credentials created using account credentials have a maximum duration of
        /// one hour.</para> <para>The federated user who holds these credentials has any permissions allowed by the intersection of the specified
        /// policy and any resource or user policies that apply to the caller of the GetFederationToken API, and any resource policies that apply to the
        /// federated user's Amazon Resource Name (ARN). For more information about how token permissions work, see Controlling Permissions in Temporary
        /// Credentials in <i>Using IAM</i> . For information about using GetFederationToken to create temporary credentials, see Creating Temporary
        /// Credentials to Enable Access for Federated Users in <i>Using IAM</i> .</para>
        /// </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)
        {
            IAsyncResult asyncResult = invokeGetFederationToken(getFederationTokenRequest, null, null, true);

            return(EndGetFederationToken(asyncResult));
        }
Пример #18
0
 /// <summary>
 /// Initiates the asynchronous execution of the GetFederationToken operation.
 /// <seealso cref="Amazon.SecurityToken.AmazonSecurityTokenService.GetFederationToken"/>
 /// </summary>
 ///
 /// <param name="getFederationTokenRequest">Container for the necessary parameters to execute the GetFederationToken operation on
 ///          AmazonSecurityTokenService.</param>
 /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
 /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
 ///          procedure using the AsyncState property.</param>
 ///
 /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
 ///         EndGetFederationToken operation.</returns>
 public IAsyncResult BeginGetFederationToken(GetFederationTokenRequest getFederationTokenRequest, AsyncCallback callback, object state)
 {
     return(invokeGetFederationToken(getFederationTokenRequest, callback, state, false));
 }