public HttpResponse DoAction <T>(AcsRequest <T> request, bool autoRetry,
                                         int maxRetryNumber, IClientProfile profile) where T : AcsResponse
        {
            if (null == profile)
            {
                throw new ClientException("SDK.InvalidProfile", "No active profile found.");
            }
            bool   retry       = autoRetry;
            int    retryNumber = maxRetryNumber;
            String region      = profile.GetRegionId();

            if (null == request.RegionId)
            {
                request.RegionId = region;
            }

            AlibabaCloudCredentials credentials = credentialsProvider.GetCredentials();

            if (credentials == null)
            {
                credentials = new DefaultCredentialProvider().GetAlibabaCloudClientCredential();
            }
            Signer          signer = Signer.GetSigner(credentials);
            FormatType      format = profile.GetFormat();
            List <Endpoint> endpoints;

            endpoints = clientProfile.GetEndpoints(request.Product, request.RegionId,
                                                   request.LocationProduct,
                                                   request.LocationEndpointType);

            return(DoAction(request, retry, retryNumber, request.RegionId, credentials, signer, format, endpoints));
        }
        public void Instance()
        {
            IClientProfile   profile;
            DefaultAcsClient instance;

            instance = new DefaultAcsClient();

            profile  = DefaultProfile.GetProfile("cn-hangzhou", AKID, AKSE);
            instance = new DefaultAcsClient(profile);
            Assert.Equal("cn-hangzhou", profile.GetRegionId());
            Assert.Equal(AKID, profile.GetCredential().AccessKeyId);
            Assert.Equal(AKSE, profile.GetCredential().AccessSecret);

            var mock = new Mock <AlibabaCloudCredentials>();
            AlibabaCloudCredentials alibabaCloudCredentials = mock.Object;

            instance = new DefaultAcsClient(profile, mock.Object);
            Assert.Equal("cn-hangzhou", profile.GetRegionId());
            Assert.Equal(AKID, profile.GetCredential().AccessKeyId);
            Assert.Equal(AKSE, profile.GetCredential().AccessSecret);

            var mockProvider = new Mock <AlibabaCloudCredentialsProvider>();
            AlibabaCloudCredentialsProvider alibabaCloudCredentialsProvider = mockProvider.Object;

            instance = new DefaultAcsClient(profile, mock.Object);
            Assert.Equal("cn-hangzhou", profile.GetRegionId());
            Assert.Equal(AKID, profile.GetCredential().AccessKeyId);
            Assert.Equal(AKSE, profile.GetCredential().AccessSecret);
        }
Exemplo n.º 3
0
        public override HttpRequest SignRequest(Signer signer, AlibabaCloudCredentials credentials,
                                                FormatType?format, ProductDomain domain)
        {
            if (this.BodyParameters != null && this.BodyParameters.Count > 0)
            {
                Dictionary <String, String> formParams = new Dictionary <String, String>(this.BodyParameters);
                string formStr  = ConcatQueryString(formParams);
                byte[] formData = System.Text.Encoding.UTF8.GetBytes(formStr);
                this.SetContent(formData, "UTF-8", FormatType.FORM);
            }

            Dictionary <string, string> imutableMap = new Dictionary <string, string>(this.Headers);

            if (null != signer && null != credentials)
            {
                String accessKeyId = credentials.GetAccessKeyId();
                imutableMap = Composer.RefreshSignParameters(Headers, signer, accessKeyId, format);
                if (credentials is BasicSessionCredentials)
                {
                    String sessionToken = ((BasicSessionCredentials)credentials).GetSessionToken();
                    if (null != sessionToken)
                    {
                        imutableMap.Add("x-acs-security-token", sessionToken);
                    }
                }

                String strToSign = Composer.ComposeStringToSign(Method, uriPattern, signer,
                                                                QueryParameters, imutableMap, pathParameters);
                String signature = signer.SignString(strToSign, credentials);
                DictionaryUtil.Add(imutableMap, "Authorization", "acs " + accessKeyId + ":" + signature);
            }
            Url          = this.ComposeUrl(domain.DomianName, QueryParameters);
            this.Headers = imutableMap;
            return(this);
        }
Exemplo n.º 4
0
        public void GetCredentials4()
        {
            // When Credentials will Expired

            // Mock Response
            HttpResponse response        = new HttpResponse();
            string       ExpiredDatetime = DateTime.Now.AddMilliseconds(800).ToString();

            byte[] content = Encoding.GetEncoding("UTF-8").GetBytes("{\"Code\":\"Success\",\"Message\":\"ThisIsMessage\",\"RequestId\":\"ThisIsRequestId\",\"AccessKeyId\":\"MockAccessKeyId\",\"AccessKeySecret\":\"\",\"SecurityToken\":\"\",\"Expiration\":\"" + ExpiredDatetime + "\"}");
            response.ContentType = FormatType.JSON;
            response.Content     = content;
            response.Status      = 200;

            // Mock Credentials
            var mockCredentials = new Mock <InstanceProfileCredentials>("MockAccessKeyId", "", "", ExpiredDatetime, 100000)
            {
                CallBase = true
            };

            mockCredentials.Setup(foo => foo.RemainTicks()).Returns(15 * 1000 * 1000 * 10);
            InstanceProfileCredentials instanceProfileCredentials = mockCredentials.Object;

            instanceProfileCredentials.SetLastFailedRefreshTime();

            // Mock Fetcher
            var mockFetcher = new Mock <ECSMetadataServiceCredentialsFetcher>()
            {
                CallBase = true
            };

            mockFetcher.Setup(foo => foo.GetResponse(
                                  It.IsAny <HttpRequest>()
                                  )).Returns(response);
            mockFetcher.Setup(foo => foo.Fetch()).Returns(instanceProfileCredentials);
            ECSMetadataServiceCredentialsFetcher fetcher = mockFetcher.Object;

            string roleName = ACKMock.GetRoleName(true);
            InstanceProfileCredentialsProvider instance = new InstanceProfileCredentialsProvider(roleName);
            AlibabaCloudCredentialsProvider    provider = instance;

            instance.withFetcher(fetcher);

            //  Credentials will Expired at first. No Throw Exception (15000 >= 10000)
            AlibabaCloudCredentials credentials = provider.GetCredentials();

            Assert.Equal("MockAccessKeyId", credentials.GetAccessKeyId());

            //  Credentials will Expired at Second. Throws Exception  (5000 < 10000)
            mockCredentials.Setup(foo => foo.RemainTicks()).Returns(5000);
            instanceProfileCredentials = mockCredentials.Object;
            instanceProfileCredentials.SetLastFailedRefreshTime();
            mockFetcher.Setup(foo => foo.Fetch()).Returns(instanceProfileCredentials);
            fetcher = mockFetcher.Object;
            instance.withFetcher(fetcher);

            Assert.Throws <ClientException>(() =>
            {
                credentials = provider.GetCredentials();
            });
        }
Exemplo n.º 5
0
        public void GetCredentials2()
        {
            // When Credentials is Expired

            // Mock Response
            HttpResponse response = new HttpResponse();

            byte[] content = Encoding.GetEncoding("UTF-8").GetBytes("{\"Code\":\"Success\",\"Message\":\"ThisIsMessage\",\"RequestId\":\"ThisIsRequestId\",\"AccessKeyId\":\"MockAccessKeyId\",\"AccessKeySecret\":\"\",\"SecurityToken\":\"\",\"Expiration\":\"" + DateTimeMock.getExpiredDateTimeString() + "\"}");
            response.ContentType = FormatType.JSON;
            response.Content     = content;
            response.Status      = 200;

            // Mock Fetcher
            var mockFetcher = new Mock <ECSMetadataServiceCredentialsFetcher>()
            {
                CallBase = true
            };

            mockFetcher.Setup(foo => foo.GetResponse(
                                  It.IsAny <HttpRequest>()
                                  )).Returns(response);
            ECSMetadataServiceCredentialsFetcher fetcher = mockFetcher.Object;

            string roleName = ACKMock.GetRoleName(true);
            InstanceProfileCredentialsProvider instance = new InstanceProfileCredentialsProvider(roleName);
            AlibabaCloudCredentialsProvider    provider = instance;

            instance.withFetcher(fetcher);

            Assert.Throws <ClientException>(() =>
            {
                AlibabaCloudCredentials credentials = provider.GetCredentials(); // 进行有效期判断,已失效则抛出异常
            });
        }
        public void DoAction1()
        {
            // When
            // request.AcceptFormat is null
            // request.ProductDomain is null
            // domain is null

            // Mock credential
            Credential credential = new Credential(AKID, AKSE);

            DefaultAcsClient instance = new DefaultAcsClient();

            // Mock AcsResquest
            MockAcsRequestForDefaultAcsClient request = new MockAcsRequestForDefaultAcsClient();

            // Mock AlibabaCloudCredentials
            var mockCredentials = new Mock <AlibabaCloudCredentials>();
            AlibabaCloudCredentials credentials = mockCredentials.Object;
            Signer signer = new HmacSHA1Signer();

            // When prodoctDomain is not exist
            Assert.Throws <ClientException>(
                () =>
            {
                var response = instance.DoAction <AcsResponse>(request, true, 1, "cn-hangzhou", credentials, signer, FormatType.JSON, null);
            }
                );
        }
 public override HttpRequest SignRequest(Signer signer, AlibabaCloudCredentials credentials,
     FormatType? format, ProductDomain domain)
 {
     var httpRequest = new HttpRequest();
     httpRequest.Url = "Instance by MockAcsRequest";
     return httpRequest;
 }
        public virtual HttpResponse DoAction <T>(AcsRequest <T> request, bool autoRetry, int maxRetryNumber, string regionId,
                                                 AlibabaCloudCredentials credentials, Signer signer, FormatType?format, List <Endpoint> endpoints) where T : AcsResponse
        {
            FormatType?requestFormatType = request.AcceptFormat;

            if (null != requestFormatType)
            {
                format = requestFormatType;
            }
            ProductDomain domain = null;

            if (request.ProductDomain != null)
            {
                domain = request.ProductDomain;
            }
            else
            {
                domain = Endpoint.FindProductDomain(regionId, request.Product, endpoints);
            }
            if (null == domain)
            {
                throw new ClientException("SDK.InvalidRegionId", "Can not find endpoint to access.");
            }

            request.Headers["User-Agent"] = UserAgent.Resolve(request.GetSysUserAgentConfig(), this.userAgentConfig);

            bool shouldRetry = true;

            for (int retryTimes = 0; shouldRetry; retryTimes++)
            {
                shouldRetry = autoRetry && retryTimes < maxRetryNumber;
                HttpRequest  httpRequest = request.SignRequest(signer, credentials, format, domain);
                HttpResponse response;

                response = this.GetResponse(httpRequest);

                PrintHttpDebugMsg(request, response);

                if (response.Content == null)
                {
                    if (shouldRetry)
                    {
                        continue;
                    }
                    else
                    {
                        throw new ClientException("SDK.ConnectionReset", "Connection reset.");
                    }
                }

                if (500 <= response.Status && shouldRetry)
                {
                    continue;
                }

                return(response);
            }

            return(null);
        }
Exemplo n.º 9
0
        public override HttpRequest SignRequest(Signer signer, AlibabaCloudCredentials credentials,
                                                FormatType?format, ProductDomain domain)
        {
            var imutableMap = new Dictionary <string, string>(QueryParameters);

            if (null != signer && null != credentials)
            {
                var accessKeyId  = credentials.GetAccessKeyId();
                var accessSecret = credentials.GetAccessKeySecret();
                switch (credentials)
                {
                case BasicSessionCredentials sessionCredentials:
                {
                    var sessionToken = sessionCredentials.GetSessionToken();
                    if (null != sessionToken)
                    {
                        QueryParameters.Add("SecurityToken", sessionToken);
                    }

                    break;
                }

                case BearerTokenCredential credential:
                {
                    var bearerToken = credential.GetBearerToken();
                    if (null != bearerToken)
                    {
                        QueryParameters.Add("BearerToken", bearerToken);
                    }

                    break;
                }
                }

                imutableMap = Composer.RefreshSignParameters(QueryParameters, signer, accessKeyId, format);
                imutableMap.Add("RegionId", RegionId);

                var paramsToSign = new Dictionary <string, string>(imutableMap);
                if (BodyParameters != null && BodyParameters.Count > 0)
                {
                    var    formParams = new Dictionary <string, string>(this.BodyParameters);
                    string formStr    = ConcatQueryString(formParams);
                    byte[] formData   = System.Text.Encoding.UTF8.GetBytes(formStr);
                    SetContent(formData, "UTF-8", FormatType.FORM);
                    foreach (var formParam in formParams)
                    {
                        DictionaryUtil.Add(paramsToSign, formParam.Key, formParam.Value);
                    }
                }

                var strToSign = this.Composer.ComposeStringToSign(Method, null, signer, paramsToSign, null, null);
                var signature = signer.SignString(strToSign, accessSecret + "&");
                imutableMap.Add("Signature", signature);

                StringToSign = strToSign;
            }

            Url = ComposeUrl(domain.DomianName, imutableMap);
            return(this);
        }
        public STSAssumeRoleSessionCredentialsProvider(AlibabaCloudCredentials longLivedCredentials, string roleArn, IAcsClient client)
        {
            AlibabaCloudCredentialsProvider longLivedCredentialsProvider = new StaticCredentialsProvider(longLivedCredentials);

            this.roleArn                    = roleArn;
            this.roleSessionName            = GetNewRoleSessionName();
            this.stsClient                  = client;
            this.roleSessionDurationSeconds = DEFAULT_DURATION_SECONDS;
        }
        public void DoAction5()
        {
            Environment.SetEnvironmentVariable("DEBUG", "sdk");
            int          status    = 200;
            string       code      = "ThisIsCode1";
            string       message   = "ThisIsMessage1";
            string       requestId = "ThisIsRequestId1";
            HttpResponse response  = new HttpResponse();

            byte[] content = Encoding.GetEncoding("UTF-8").GetBytes("{\"Code\":\"" + code + "\",\"Message\":\"" + message + "\",\"RequestId\":\"" + requestId + "\"}");
            response.ContentType = FormatType.JSON;
            response.Content     = content;
            response.Status      = status;

            Dictionary <string, string> tmpHeaders = new Dictionary <string, string>
            {
                { "Content-MD5", "md5" },
                { "Content-Length", "length" },
                { "Content-Type", "text/json" }
            };

            response.Headers = tmpHeaders;

            var mockInstance = new Mock <DefaultAcsClient>()
            {
                CallBase = true
            };

            mockInstance.Setup(foo => foo.GetResponse(
                                   It.IsAny <HttpRequest>()
                                   )).Returns(response);

            DefaultAcsClient instance = mockInstance.Object;

            // Mock AcsResquest
            MockAcsRequestForDefaultAcsClient request = new MockAcsRequestForDefaultAcsClient();

            request.AcceptFormat = FormatType.JSON;
            ProductDomain productDomain = new ProductDomain("productName1", "productDomain1");

            request.ProductDomain = productDomain;

            // Mock AlibabaCloudCredentials
            var mockCredentials = new Mock <AlibabaCloudCredentials>();
            AlibabaCloudCredentials credentials = mockCredentials.Object;

            // Mock Signer
            Signer signer = new HmacSHA1Signer();

            var result = instance.DoAction <AcsResponse>(request, true, 1, "cn-hangzhou", credentials, signer, FormatType.JSON, null);

            Assert.Null(Environment.GetEnvironmentVariable("DEBUG"));

            status = 500;
            result = instance.DoAction <AcsResponse>(request, true, 0, "cn-hangzhou", credentials, signer, FormatType.JSON, null);
            Assert.Null(Environment.GetEnvironmentVariable("DEBUG"));
        }
Exemplo n.º 12
0
        public void AlibabaCloudCredentialsInstance()
        {
            var mock = new Mock <AlibabaCloudCredentials>();

            AlibabaCloudCredentials   credentials = mock.Object;
            StaticCredentialsProvider instance    = new StaticCredentialsProvider(credentials); // 无回调

            // DONE WITH NO EXCEPTION
        }
        public static Signer GetSigner(AlibabaCloudCredentials credentials)
        {
            if (credentials is BearerTokenCredential)
            {
                return(bearerTokenSigner);
            }

            return(credentials is KeyPairCredentials ? sha256withRSASigner : hmacSHA1Signer);
        }
Exemplo n.º 14
0
        public STSAssumeRoleSessionCredentialsProvider(AlibabaCloudCredentials longLivedCredentials,
                                                       String roleArn, IClientProfile clientProfile)
        {
            AlibabaCloudCredentialsProvider longLivedCredentialsProvider = new StaticCredentialsProvider(longLivedCredentials);

            this.roleArn                    = roleArn;
            this.roleSessionName            = GetNewRoleSessionName();
            this.stsClient                  = new DefaultAcsClient(clientProfile, longLivedCredentialsProvider);
            this.roleSessionDurationSeconds = DEFAULT_DURATION_SECONDS;
        }
Exemplo n.º 15
0
        public async Task <HttpResponse> DoActionAsync <T>(AcsRequest <T> request, bool autoRetry, int maxRetryNumber, string regionId,
                                                           AlibabaCloudCredentials credentials, Signer signer, FormatType?format, List <Endpoint> endpoints, CancellationToken ct) where T : AcsResponse
        {
            FormatType?requestFormatType = request.AcceptFormat;

            if (null != requestFormatType)
            {
                format = requestFormatType;
            }
            ProductDomain domain = null;

            if (request.ProductDomain != null)
            {
                domain = request.ProductDomain;
            }
            else
            {
                domain = Endpoint.FindProductDomain(regionId, request.Product, endpoints);
            }
            if (null == domain)
            {
                throw new ClientException("SDK.InvalidRegionId", "Can not find endpoint to access.");
            }

            bool shouldRetry = true;

            for (int retryTimes = 0; shouldRetry; retryTimes++)
            {
                shouldRetry = autoRetry && retryTimes < maxRetryNumber;
                HttpRequest  httpRequest = request.SignRequest(signer, credentials, format, domain);
                HttpResponse response;
                response = await HttpResponse.GetResponseAsync(httpRequest, ct).ConfigureAwait(false);

                if (response.Content == null)
                {
                    if (shouldRetry)
                    {
                        continue;
                    }
                    else
                    {
                        throw new ClientException("SDK.ConnectionReset", "Connection reset.");
                    }
                }

                if (500 <= response.Status && shouldRetry)
                {
                    continue;
                }

                return(response);
            }

            return(null);
        }
Exemplo n.º 16
0
        public void DoAction()
        {
            // Mock RegionIds
            ISet <String> regionIds = new HashSet <String>();

            regionIds.Add("cn-hangzhou");

            // Mock productDomains
            List <ProductDomain> productDomains = new List <ProductDomain>()
            {
            };

            // Mock endpoint
            Endpoint endpoint = new Endpoint("cn-hangzhou", regionIds, productDomains);

            // Mock endpoints
            List <Endpoint> endpoints = new List <Endpoint>()
            {
            };

            endpoints.Add(endpoint);

            // Mock credential
            Credential credential = new Credential(AKID, AKSE);

            // Mock Profile
            var mockProfile = new Mock <IClientProfile>();

            mockProfile.Setup(foo => foo.GetCredential()).Returns(credential);
            IClientProfile profile = mockProfile.Object;

            DefaultAcsClient instance = new DefaultAcsClient();

            // Mock AcsResquest
            MockAcsRequestForDefaultAcsClient request = new MockAcsRequestForDefaultAcsClient();

            request.RegionId             = "cn-hangzhou";
            request.Product              = "Ess";
            request.LocationProduct      = "ess";
            request.LocationEndpointType = "openAPI";

            // Mock AlibabaCloudCredentials
            var mockCredentials = new Mock <AlibabaCloudCredentials>();
            AlibabaCloudCredentials credentials = mockCredentials.Object;
            Signer signer = new HmacSHA1Signer();

            // When prodoctDomain is not exist
            Assert.Throws <ClientException>(
                () =>
            {
                var response = instance.DoAction <AcsResponse>(request, true, 1, "cn-hangzhou", credentials, signer, FormatType.JSON, endpoints);
            }
                );
        }
Exemplo n.º 17
0
        public STSAssumeRoleSessionCredentialsProvider(
            AlibabaCloudCredentials longLivedCredentials,
            string roleArn,
            IClientProfile clientProfile)
        {
            AlibabaCloudCredentialsProvider longLivedCredentialsProvider = new StaticCredentialsProvider(longLivedCredentials);

            this.roleArn    = roleArn;
            roleSessionName = GetNewRoleSessionName();
            stsClient       = new DefaultAcsClient(clientProfile, longLivedCredentialsProvider);
        }
Exemplo n.º 18
0
        public void Instance()
        {
            var mock = new Mock <AlibabaCloudCredentials>();
            AlibabaCloudCredentials longLivedCredentials = mock.Object;
            string         roleArn = "roleArn";
            IClientProfile profile = DefaultProfile.GetProfile("cn-shanghai", "accessKeyId", "accessKeySecret");

            STSAssumeRoleSessionCredentialsProvider instance = new STSAssumeRoleSessionCredentialsProvider(longLivedCredentials, roleArn, profile);

            Assert.NotNull(instance);
        }
Exemplo n.º 19
0
        public STSAssumeRoleSessionCredentialsProvider(
            AlibabaCloudCredentials longLivedCredentials,
            string roleArn,
            IAcsClient client)
        {
            AlibabaCloudCredentialsProvider longLivedCredentialsProvider = new StaticCredentialsProvider(longLivedCredentials);

            this.roleArn    = roleArn;
            roleSessionName = GetNewRoleSessionName();
            stsClient       = client;
        }
Exemplo n.º 20
0
 public static Signer GetSigner(AlibabaCloudCredentials credentials)
 {
     if (credentials is KeyPairCredentials)
     {
         return(sha256withRSASigner);
     }
     else
     {
         return(hmacSHA1Signer);
     }
 }
Exemplo n.º 21
0
        public void WithRoleSessionName()
        {
            var mock = new Mock <AlibabaCloudCredentials>();
            AlibabaCloudCredentials longLivedCredentials = mock.Object;
            string         roleArn = "roleArn";
            IClientProfile profile = DefaultProfile.GetProfile("cn-shanghai", "accessKeyId", "accessKeySecret");
            STSAssumeRoleSessionCredentialsProvider instance = new STSAssumeRoleSessionCredentialsProvider(longLivedCredentials, roleArn, profile);

            instance.WithRoleSessionName("roleSessionName"); // 方法回调 STSAssumeRoleSessionCredentialsProvider 实例

            Assert.IsType <STSAssumeRoleSessionCredentialsProvider>(instance);
        }
Exemplo n.º 22
0
        public void Instance()
        {
            MockSigner instance = new MockSigner();
            var        mock     = new Mock <AlibabaCloudCredentials>();
            AlibabaCloudCredentials credentials = mock.Object;

            Assert.IsType <HmacSHA1Signer>(MockSigner.GetSigner(credentials));

            KeyPairCredentials KeyPairCredentials = new KeyPairCredentials("publicKeyId", "privateKeySecret");

            Assert.IsType <SHA256withRSASigner>(MockSigner.GetSigner(KeyPairCredentials));
        }
        public void DoAction3()
        {
            // When
            // request.AcceptFormat is not null
            // request.ProductDomain is not null
            // domain is not null
            // response.Content is not null
            // response.Status != 200

            // Mock response
            int          status    = 400;
            string       code      = "ThisIsCode";
            string       message   = "ThisIsMessage";
            string       requestId = "ThisIsRequestId";
            HttpResponse response  = new HttpResponse();

            byte[] content = Encoding.GetEncoding("UTF-8").GetBytes("{\"Code\":\"" + code + "\",\"Message\":\"" + message + "\",\"RequestId\":\"" + requestId + "\"}");
            response.ContentType = FormatType.JSON;
            response.Content     = content;
            response.Status      = status;

            var mockInstance = new Mock <DefaultAcsClient>()
            {
                CallBase = true
            };

            mockInstance.Setup(foo => foo.GetResponse(
                                   It.IsAny <HttpRequest>()
                                   )).Returns(response);

            DefaultAcsClient instance = mockInstance.Object;

            // Mock AcsResquest
            MockAcsRequestForDefaultAcsClient request = new MockAcsRequestForDefaultAcsClient();

            request.AcceptFormat = FormatType.JSON;
            ProductDomain productDomain = new ProductDomain("productName", "productDomain");

            request.ProductDomain = productDomain;

            // Mock AlibabaCloudCredentials
            var mockCredentials = new Mock <AlibabaCloudCredentials>();
            AlibabaCloudCredentials credentials = mockCredentials.Object;

            // Mock Signer
            Signer signer = new HmacSHA1Signer();

            var result = instance.DoAction <AcsResponse>(request, true, 1, "cn-hangzhou", credentials, signer, FormatType.JSON, null);

            Assert.NotNull(result);
            Assert.Equal(result.Status, response.Status);
        }
        public string GetSecurityToken()
        {
            AlibabaCloudCredentials credentials = GetCredentials();

            if (credentials is BasicSessionCredentials)
            {
                return(((BasicSessionCredentials)credentials).GetSessionToken());
            }
            else
            {
                return(null);
            }
        }
        public override HttpRequest SignRequest(Signer signer, AlibabaCloudCredentials credentials,
                                                FormatType?format, ProductDomain domain)
        {
            if (BodyParameters != null && BodyParameters.Count > 0)
            {
                var    formParams = new Dictionary <string, string>(this.BodyParameters);
                string formStr    = ConcatQueryString(formParams);
                byte[] formData   = System.Text.Encoding.UTF8.GetBytes(formStr);
                SetContent(formData, "UTF-8", FormatType.FORM);
            }

            var imutableMap = new Dictionary <string, string>(this.Headers);

            if (null != signer && null != credentials)
            {
                var accessKeyId = credentials.GetAccessKeyId();
                imutableMap = Composer.RefreshSignParameters(Headers, signer, accessKeyId, format);
                switch (credentials)
                {
                case BasicSessionCredentials sessionCredentials:
                {
                    var sessionToken = sessionCredentials.GetSessionToken();
                    if (null != sessionToken)
                    {
                        imutableMap.Add("x-acs-security-token", sessionToken);
                    }

                    break;
                }

                case BearerTokenCredential credential:
                {
                    var bearerToken = credential.GetBearerToken();
                    if (null != bearerToken)
                    {
                        QueryParameters.Add("x-acs-bearer-token", bearerToken);
                    }

                    break;
                }
                }

                var strToSign = Composer.ComposeStringToSign(Method, UriPattern, signer,
                                                             QueryParameters, imutableMap, PathParameters);
                var signature = signer.SignString(strToSign, credentials);
                DictionaryUtil.Add(imutableMap, "Authorization", "acs " + accessKeyId + ":" + signature);
            }
            Url     = ComposeUrl(domain.DomianName, QueryParameters);
            Headers = imutableMap;
            return(this);
        }
        public void SignRequest()
        {
            MockRoaAcsRequest       mockRoaAcsRequest       = new MockRoaAcsRequest("product");
            HmacSHA1Signer          signer                  = new HmacSHA1Signer();
            BasicSessionCredentials basicSessionCredentials = new BasicSessionCredentials(
                "accessKeyId", "accessKeySecret", "sessionToken", 0
                );
            ProductDomain domain = new ProductDomain();

            mockRoaAcsRequest.UriPattern = "UriPattern";
            Dictionary <string, string> tmpDic = new Dictionary <string, string>
            {
                { "a", "A" },
                { "b", "B" }
            };

            mockRoaAcsRequest.BodyParameters = tmpDic;
            mockRoaAcsRequest.PathParameters = tmpDic;
            mockRoaAcsRequest.UriPattern     = "UriPattern";
            Assert.Equal("UriPattern", mockRoaAcsRequest.UriPattern);

            var request = mockRoaAcsRequest.SignRequest(signer, basicSessionCredentials, FormatType.JSON, domain);

            Assert.IsType <MockRoaAcsRequest>(request);
            basicSessionCredentials = new BasicSessionCredentials(
                "accessKeyId", "accessKeySecret", null, 0
                );
            request = mockRoaAcsRequest.SignRequest(signer, basicSessionCredentials, FormatType.JSON, domain);

            // 覆盖不同条件的执行
            mockRoaAcsRequest.BodyParameters = null;
            signer = null;
            var mockCredential = new Mock <AlibabaCloudCredentials>();

            mockCredential.Setup(foo => foo.GetAccessKeyId()).Returns("accessKeyId");
            mockCredential.Setup(foo => foo.GetAccessKeySecret()).Returns("accessKeySecret");
            AlibabaCloudCredentials credential = mockCredential.Object;

            mockRoaAcsRequest.SignRequest(signer, credential, FormatType.JSON, domain);

            signer = new HmacSHA1Signer();
            mockRoaAcsRequest.SignRequest(signer, credential, FormatType.JSON, domain);

            //Test Bearertoken SignRequest with Rpc
            mockRoaAcsRequest.BodyParameters = null;
            BearerTokenSigner     bearerTokenSigner     = new BearerTokenSigner();
            BearerTokenCredential bearerTokenCredential = new BearerTokenCredential("FakeBearerToken");

            mockRoaAcsRequest.SignRequest(bearerTokenSigner, bearerTokenCredential, FormatType.JSON, domain);
        }
Exemplo n.º 27
0
        public static Signer GetSigner(AlibabaCloudCredentials credentials)
        {
            switch (credentials)
            {
            case BearerTokenCredential _:
                return(bearerTokenSigner);

            case KeyPairCredentials _:
                return(sha256withRSASigner);

            default:
                return(hmacSHA1Signer);
            }
        }
        public void DoAction2()
        {
            // When
            // request.AcceptFormat is not null
            // request.ProductDomain is not null
            // domain is not null
            // response.Content is null

            // Mock response
            HttpResponse response = new HttpResponse();

            response.ContentType = FormatType.JSON;
            response.Content     = null;
            response.Status      = 200;

            var mockInstance = new Mock <DefaultAcsClient>()
            {
                CallBase = true
            };

            mockInstance.Setup(foo => foo.GetResponse(
                                   It.IsAny <HttpRequest>()
                                   )).Returns(response);

            DefaultAcsClient instance = mockInstance.Object;

            // Mock AcsResquest
            MockAcsRequestForDefaultAcsClient request = new MockAcsRequestForDefaultAcsClient();

            request.AcceptFormat = FormatType.JSON;
            ProductDomain productDomain = new ProductDomain("productName", "productDomain");

            request.ProductDomain = productDomain;

            // Mock AlibabaCloudCredentials
            var mockCredentials = new Mock <AlibabaCloudCredentials>();
            AlibabaCloudCredentials credentials = mockCredentials.Object;

            // Mock Signer
            Signer signer = new HmacSHA1Signer();

            Assert.Throws <ClientException>(
                () =>
            {
                var result = instance.DoAction <AcsResponse>(request, true, 1, "cn-hangzhou", credentials, signer, FormatType.JSON, null);
            }
                );
        }
        public StaticCredentialsProvider(IClientProfile clientProfile)
        {
            this.clientProfile = clientProfile;
            var legacyCredential = this.clientProfile.GetCredential();

            if (null != legacyCredential.SecurityToken)
            {
                credentials = new BasicSessionCredentials(
                    legacyCredential.AccessKeyId,
                    legacyCredential.AccessSecret,
                    legacyCredential.SecurityToken);
            }
            else
            {
                credentials = new LegacyCredentials(legacyCredential);
            }
        }
Exemplo n.º 30
0
        public void SignString()
        {
            SHA256withRSASigner instance = new SHA256withRSASigner();

            // 结果每次都是不同的
            string str = instance.SignString("foo", "secret");

            Assert.NotEmpty(str);

            var mock = new Mock <AlibabaCloudCredentials>();

            mock.Setup(foo => foo.GetAccessKeySecret()).Returns("secret");
            AlibabaCloudCredentials credentials = mock.Object;
            string str2 = instance.SignString("foo", credentials);

            Assert.NotEmpty(str2);
        }