/// <summary> /// Make an HTTP request to CHES to get an access token for the specified 'username' and 'password'. /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> public async Task <TokenModel> GetTokenAsync(string username = null, string password = null) { var headers = new HttpRequestMessage().Headers; var creds = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes($"{username ?? this.Options.Username}:{password ?? this.Options.Password}")); headers.Add("Authorization", $"Basic {creds}"); headers.Add("ContentType", "application/x-www-form-urlencoded"); var form = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("grant_type", "client_credentials") }; var content = new FormUrlEncodedContent(form); try { return(await this.Client.SendAsync <TokenModel>(this.Options.AuthUrl, HttpMethod.Post, headers, content)); } catch (HttpClientRequestException ex) { _logger.LogError(ex, $"Failed to send/receive request: ${this.Options.AuthUrl}"); var response = await this.Client?.DeserializeAsync <Ches.Models.ErrorResponseModel>(ex.Response); throw new ChesException(ex, this.Client, response); } }
private static IHeadersCollection InjectContext(string traceId, string spanId, string samplingPriority) { IHeadersCollection headers = new HttpRequestMessage().Headers.Wrap(); headers.Add(B3HttpHeaderNames.B3TraceId, traceId); headers.Add(B3HttpHeaderNames.B3SpanId, spanId); // Mimick the B3 injection mapping of samplingPriority switch (samplingPriority) { case "-1": // SamplingPriority.UserReject case "0": // SamplingPriority.AutoReject headers.Add(B3HttpHeaderNames.B3Flags, "0"); break; case "1": // SamplingPriority.AutoKeep headers.Add(B3HttpHeaderNames.B3Sampled, "1"); break; case "2": // SamplingPriority.UserKeep headers.Add(B3HttpHeaderNames.B3Flags, "1"); break; default: // Invalid samplingPriority break; } return(headers); }
private static IHeadersCollection InjectContext(string traceId, string spanId, string samplingPriority) { IHeadersCollection headers = new HttpRequestMessage().Headers.Wrap(); headers.Add(HttpHeaderNames.B3TraceId, traceId); headers.Add(HttpHeaderNames.B3SpanId, spanId); headers.Add(HttpHeaderNames.B3Sampled, samplingPriority); return(headers); }
public void ShouldInitializeFromHttpHeaders() { var httpHeaders = new HttpRequestMessage().Headers; httpHeaders.Add(HeaderTypes.Authorization, "the-xx"); httpHeaders.Add(HeaderTypes.XForwardedFor, new[] { "192.168.1.1", "127.0.0.1" }); var headers = new FluentHttpHeaders(httpHeaders); Assert.Equal("the-xx", headers.Authorization); Assert.Equal("192.168.1.1,127.0.0.1", headers.XForwardedFor); Assert.Equal(2, headers.Count); }
static void Main(string[] args) { using (HttpClient httpClient = new HttpClient()) { RestTemplate rest = new RestTemplate(httpClient); Console.WriteLine("---查询数据---------"); var headers = new HttpRequestMessage().Headers; headers.Add("aa", "666"); var ret1 = rest.GetForEntityAsync <Product[]>("http://ProductService/api/Product/", headers).Result; Console.WriteLine(ret1.StatusCode); if (ret1.StatusCode == System.Net.HttpStatusCode.OK) { foreach (var p in ret1.Body) { Console.WriteLine($"id={p.Id},name={p.Name}"); } } Console.WriteLine("---新增数据---------"); Product newP = new Product(); newP.Id = 888; newP.Name = "辛增"; newP.Price = 88.8; var ret = rest.PostAsync("http://ProductService/api/Product/", newP).Result; Console.WriteLine(ret.StatusCode); } Console.ReadKey(); }
public async Task <IActionResult> Invoke([FromBody] JToken body) { var invokeHeaders = ProcessInvokeHeaders(); if (string.IsNullOrWhiteSpace(invokeHeaders.Path)) { return(BadRequest($"Missing {PathQueryHeader} header")); } var detectorId = body?["id"] != null ? body["id"].ToString() : string.Empty; string applensLink = "https://applens.azurewebsites.net/" + invokeHeaders.Path.Replace("resourcegroup", "resourceGroup").Replace("diagnostics/publish", string.Empty) + "detectors/" + detectorId; var detectorAuthorEmails = new List <EmailAddress>(); if (invokeHeaders.DetectorAuthors.Any()) { detectorAuthorEmails = invokeHeaders.DetectorAuthors .Select(x => x.EndsWith("@microsoft.com") ? x : $"{x}@microsoft.com") .Distinct(StringComparer.OrdinalIgnoreCase) .Select(x => new EmailAddress(x)).ToList(); } HttpRequestHeaders headers = new HttpRequestMessage().Headers; foreach (var header in Request.Headers) { if ((header.Key.StartsWith("x-ms-") || header.Key.StartsWith("diag-")) && !headers.Contains(header.Key)) { headers.Add(header.Key, header.Value.ToString()); } } var response = await DiagnosticClient.Execute(invokeHeaders.Method, invokeHeaders.Path, body?.ToString(), invokeHeaders.InternalClient, invokeHeaders.InternalView, headers); if (response == null) { return(StatusCode(500, "Null response from DiagnosticClient")); } var responseTask = response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { return(StatusCode((int)response.StatusCode, await responseTask)); } if (response.Headers.Contains(ScriptEtagHeader)) { Request.HttpContext.Response.Headers.Add(ScriptEtagHeader, response.Headers.GetValues(ScriptEtagHeader).First()); } if (invokeHeaders.Path.EndsWith("/diagnostics/publish", StringComparison.OrdinalIgnoreCase) && detectorAuthorEmails.Count > 0 && Env.IsProduction()) { EmailNotificationService.SendPublishingAlert(invokeHeaders.DetectorAuthors.Last(), detectorId, applensLink, detectorAuthorEmails); } return(Ok(JsonConvert.DeserializeObject(await responseTask))); }
public void LogController_ExtractSessionId_EmptySessionToken_SessionIdReturnsEmptyString() { var token = ""; var headers = new HttpRequestMessage().Headers; headers.Add(ServiceConstants.BlueprintSessionTokenKey, token); var sessionId = LogController.ExtractSessionId(headers); Assert.AreEqual(string.Empty, sessionId); }
public void LogController_ExtractSessionId_SessionTokenToShort_SessionIdReturnsWholeToken() { var token = "token"; var headers = new HttpRequestMessage().Headers; headers.Add(ServiceConstants.BlueprintSessionTokenKey, token); var sessionId = LogController.ExtractSessionId(headers); Assert.AreEqual(token, sessionId); }
public void LogController_ExtractSessionId_SessionTokenMoreThen8Chars_SessionIdReturnsFirst8Chars() { var token = "1E6207CE-6AB4-438F-8F87-9C76BEB95FB8"; var headers = new HttpRequestMessage().Headers; headers.Add(ServiceConstants.BlueprintSessionTokenKey, token); var sessionId = LogController.ExtractSessionId(headers); Assert.AreEqual("1E6207CE", sessionId); }
public void TransformHeaderNamesToLowercase(string headerName, string expected) { // Arrange var headers = new HttpRequestMessage().Headers; headers.Add(headerName, "some header value"); // Act var actual = CanonicalRequest.SortHeaders(headers, null); // Assert actual.Keys.ShouldBe(new[] { expected }); }
public void RemoveSequentialSpacesInHeaderValue(string headerValue, string expected) { // Arrange var headers = new HttpRequestMessage().Headers; headers.Add("some-header-name", headerValue); // Act var actual = CanonicalRequest.SortHeaders(headers, null); // Assert actual["some-header-name"].ShouldBe(new[] { expected }); }
public void RespectDefaultHeader() { // Arrange var headers = new HttpRequestMessage().Headers; var defaultHeaders = new HttpRequestMessage().Headers; defaultHeaders.Add("some-header-name", "some-header-value"); // Act var actual = CanonicalRequest.SortHeaders(headers, defaultHeaders); // Assert actual["some-header-name"].ShouldBe(new[] { "some-header-value" }); }
public void SortHeaderNames(string[] headerNames, string[] expected) { // Arrange var headers = new HttpRequestMessage().Headers; foreach (var headerName in headerNames) { headers.Add(headerName, "some header value"); } // Act var actual = CanonicalRequest.SortHeaders(headers, null); // Assert actual.Keys.ShouldBe(expected); }
/// <summary> /// Send a request to the specified endpoint. /// </summary> /// <typeparam name="TR"></typeparam> /// <param name="endpoint"></param> /// <param name="method"></param> /// <returns></returns> private async Task <TR> SendAsync <TR>(string endpoint, HttpMethod method) { await RefreshAccessTokenAsync(); var url = GenerateUrl(endpoint); var headers = new HttpRequestMessage().Headers; headers.Add("Authorization", $"Bearer {_token.AccessToken}"); try { return(await this.Client.SendAsync <TR>(url, method, headers)); } catch (HttpClientRequestException ex) { var response = await this.Client?.DeserializeAsync <Ches.Models.ErrorResponseModel>(ex.Response); throw new ChesException(ex, this.Client, response); } }
/// <summary> /// Send a request to the specified endpoint. /// Make a request to get an access token if required. /// </summary> /// <typeparam name="TR"></typeparam> /// <typeparam name="TD"></typeparam> /// <param name="endpoint"></param> /// <param name="method"></param> /// <param name="data"></param> /// <returns></returns> private async Task <TR> SendAsync <TR, TD>(string endpoint, HttpMethod method, TD data) where TD : class { await RefreshAccessTokenAsync(); var url = GenerateUrl(endpoint); var headers = new HttpRequestMessage().Headers; headers.Add("Authorization", $"Bearer {_token.AccessToken}"); try { return(await this.Client.SendJsonAsync <TR, TD>(url, method, headers, data)); } catch (HttpClientRequestException ex) { _logger.LogError(ex, $"Failed to send/receive request: ${url}"); var response = await this.Client?.DeserializeAsync <Ches.Models.ErrorResponseModel>(ex.Response); throw new ChesException(ex, this.Client, response); } }
/// <summary> /// Send a request to the specified endpoint. /// </summary> /// <typeparam name="TR"></typeparam> /// <param name="endpoint"></param> /// <param name="method"></param> /// <returns></returns> private async Task <string> SendAsync(string endpoint, HttpMethod method) { await RefreshAccessTokenAsync(); var url = GenerateUrl(endpoint); var headers = new HttpRequestMessage().Headers; headers.Add("Authorization", $"Bearer {_token.AccessToken}"); try { var response = await this.Client.SendAsync(url, method, headers); return(await response.Content.ReadAsStringAsync()); } catch (HttpClientRequestException ex) { _logger.LogError(ex, $"Failed to send/receive request: {ex.StatusCode} {url}"); var response = await this.Client?.DeserializeAsync <Ches.Models.ErrorResponseModel>(ex.Response); throw new ChesException(ex, this.Client, response); } }
public async Task SendActive() { HttpResponseMessage httpResponse = new HttpResponseMessage { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent("", Encoding.UTF8, "application/json") }; Mock <HttpMessageHandler> mockHandler = new Mock <HttpMessageHandler>(); mockHandler.Protected().Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>() ).ReturnsAsync(httpResponse); var fsLogManagerMock = new Mock <IFsLogManager>(); var config = new Flagship.Config.DecisionApiConfig { ApiKey = "apiKey", EnvId = "envId", LogManager = fsLogManagerMock.Object, }; var httpClient = new HttpClient(mockHandler.Object); var trackingManager = new Flagship.Api.TrackingManager(config, httpClient); var decisionManagerMock = new Mock <Flagship.Decision.IDecisionManager>(); var configManager = new Flagship.Config.ConfigManager(config, decisionManagerMock.Object, trackingManager); var context = new Dictionary <string, object>(); var visitorDelegate = new Flagship.FsVisitor.VisitorDelegate("visitorId", false, context, true, configManager); var flag = new Flagship.Model.FlagDTO() { VariationGroupId = "varGroupID", VariationId = "varID", }; var postData = new Dictionary <string, object> { [Constants.VISITOR_ID_API_ITEM] = visitorDelegate.VisitorId, [Constants.VARIATION_ID_API_ITEM] = flag.VariationId, [Constants.VARIATION_GROUP_ID_API_ITEM] = flag.VariationGroupId, [Constants.CUSTOMER_ENV_ID_API_ITEM] = config.EnvId, [Constants.ANONYMOUS_ID] = null }; Func <HttpRequestMessage, bool> action = (HttpRequestMessage x) => { var postDataString = JsonConvert.SerializeObject(postData); var headers = new HttpRequestMessage().Headers; headers.Add(Constants.HEADER_X_API_KEY, config.ApiKey); headers.Add(Constants.HEADER_X_SDK_CLIENT, Constants.SDK_LANGUAGE); headers.Add(Constants.HEADER_X_SDK_VERSION, Constants.SDK_VERSION); headers.Accept.Add(new MediaTypeWithQualityHeaderValue(Constants.HEADER_APPLICATION_JSON)); var result = x.Content.ReadAsStringAsync().Result; return(result == postDataString && headers.ToString() == x.Headers.ToString() && x.Method == HttpMethod.Post); }; var errorSendAsyn = new Exception("Error Send"); mockHandler.Protected().Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.Is <HttpRequestMessage>(x => action(x)), ItExpr.IsAny <CancellationToken>() ).ReturnsAsync(httpResponse).Verifiable(); await trackingManager.SendActive(visitorDelegate, flag).ConfigureAwait(false); // XC test mockHandler.Protected().Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.Is <HttpRequestMessage>(x => action(x)), ItExpr.IsAny <CancellationToken>() ).ReturnsAsync(httpResponse).Verifiable(); var newVisitorId = "newVisitorId"; visitorDelegate.Authenticate(newVisitorId); postData[Constants.VISITOR_ID_API_ITEM] = visitorDelegate.VisitorId; postData[Constants.ANONYMOUS_ID] = visitorDelegate.AnonymousId; await trackingManager.SendActive(visitorDelegate, flag).ConfigureAwait(false); mockHandler.Verify(); httpResponse.Dispose(); httpClient.Dispose(); }
public async Task <IActionResult> Invoke([FromBody] JToken body) { var invokeHeaders = ProcessInvokeHeaders(); if (string.IsNullOrWhiteSpace(invokeHeaders.Path)) { return(BadRequest($"Missing {PathQueryHeader} header")); } string detectorId = null; if (body?.GetType() != typeof(JArray)) { detectorId = body?["id"] != null ? body["id"].ToString() : string.Empty; } string applensLink = "https://applens.azurewebsites.net/" + invokeHeaders.Path.Replace("resourcegroup", "resourceGroup").Replace("diagnostics/publish", string.Empty) + "detectors/" + detectorId; var detectorAuthorEmails = new List <EmailAddress>(); if (invokeHeaders.DetectorAuthors.Any()) { detectorAuthorEmails = invokeHeaders.DetectorAuthors .Select(x => x.EndsWith("@microsoft.com") ? x : $"{x}@microsoft.com") .Distinct(StringComparer.OrdinalIgnoreCase) .Select(x => new EmailAddress(x)).ToList(); } HttpRequestHeaders headers = new HttpRequestMessage().Headers; var locationPlacementId = await GetLocationPlacementId(invokeHeaders); if (!string.IsNullOrWhiteSpace(locationPlacementId)) { headers.Add("x-ms-subscription-location-placementid", locationPlacementId); } foreach (var header in Request.Headers) { if ((header.Key.StartsWith("x-ms-") || header.Key.StartsWith("diag-")) && !headers.Contains(header.Key)) { headers.Add(header.Key, header.Value.ToString()); } } // For Publishing Detector Calls, validate if user has access to publish the detector if (invokeHeaders.Path.EndsWith("/diagnostics/publish", StringComparison.OrdinalIgnoreCase)) { if (!TryFetchPublishAcessParametersFromRequestBody(body, out string resourceType, out string detectorCode, out bool isOriginalCodeMarkedPublic, out string errMsg)) { return(BadRequest(errMsg)); } string userAlias = Utilities.GetUserIdFromToken(Request.Headers["Authorization"].ToString()); var resourceConfig = await this.resourceConfigService.GetResourceConfig(resourceType); bool hasAccess = await Utilities.IsUserAllowedToPublishDetector(userAlias, resourceConfig, detectorCode, isOriginalCodeMarkedPublic); if (!hasAccess) { return(Unauthorized()); } } var response = await DiagnosticClient.Execute(invokeHeaders.Method, invokeHeaders.Path, body?.ToString(), invokeHeaders.InternalClient, invokeHeaders.InternalView, headers); if (response == null) { return(StatusCode(500, "Null response from DiagnosticClient")); } var responseTask = response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { return(StatusCode((int)response.StatusCode, await responseTask)); } if (response.Headers.Contains(ScriptEtagHeader)) { Request.HttpContext.Response.Headers.Add(ScriptEtagHeader, response.Headers.GetValues(ScriptEtagHeader).First()); } if (invokeHeaders.Path.EndsWith("/diagnostics/publish", StringComparison.OrdinalIgnoreCase) && detectorAuthorEmails.Count > 0 && Env.IsProduction()) { EmailNotificationService.SendPublishingAlert(invokeHeaders.ModifiedBy, detectorId, applensLink, detectorAuthorEmails); } return(Ok(JsonConvert.DeserializeObject(await responseTask))); }
public async Task <IActionResult> Invoke([FromBody] JToken body) { if (!Request.Headers.ContainsKey("x-ms-path-query")) { return(BadRequest("Missing x-ms-path-query header")); } string path = Request.Headers["x-ms-path-query"]; string method = HttpMethod.Get.Method; if (Request.Headers.ContainsKey("x-ms-method")) { method = Request.Headers["x-ms-method"]; } bool internalClient = true; if (Request.Headers.ContainsKey("x-ms-internal-client")) { bool.TryParse(Request.Headers["x-ms-internal-client"], out internalClient); } bool internalView = true; if (Request.Headers.ContainsKey("x-ms-internal-view")) { bool.TryParse(Request.Headers["x-ms-internal-view"], out internalView); } string alias = string.Empty; string detectorId = string.Empty; string detectorAuthor = string.Empty; List <EmailAddress> tos = new List <EmailAddress>(); List <string> distinctEmailRecipientsList = new List <string>(); if (body != null && body["id"] != null) { detectorId = body["id"].ToString(); } string applensLink = "https://applens.azurewebsites.net/" + path.Replace("resourcegroup", "resourceGroup").Replace("diagnostics/publish", "") + "detectors/" + detectorId; if (!string.IsNullOrWhiteSpace(Request.Headers["x-ms-emailRecipients"])) { detectorAuthor = Request.Headers["x-ms-emailRecipients"]; char[] separators = { ' ', ',', ';', ':' }; // Currently there's a bug in sendgrid v3, email will not be sent if there are duplicates in the recipient list // Remove duplicates before adding to the recipient list string[] authors = detectorAuthor.Split(separators, StringSplitOptions.RemoveEmptyEntries).Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); foreach (var author in authors) { if (string.IsNullOrWhiteSpace(alias)) { alias = author; } string baseEmailAddressString = author.EndsWith("@microsoft.com", StringComparison.OrdinalIgnoreCase) ? author : author + "@microsoft.com"; if (!distinctEmailRecipientsList.Contains(baseEmailAddressString)) { EmailAddress emailAddress = new EmailAddress(baseEmailAddressString); tos.Add(emailAddress); distinctEmailRecipientsList.Add(baseEmailAddressString); } } } var scriptETag = string.Empty; if (Request.Headers.ContainsKey("diag-script-etag")) { scriptETag = Request.Headers["diag-script-etag"]; } var assemblyName = string.Empty; if (Request.Headers.ContainsKey("diag-assembly-name")) { assemblyName = Request.Headers["diag-assembly-name"]; } HttpRequestHeaders headers = new HttpRequestMessage().Headers; if (!string.IsNullOrWhiteSpace(scriptETag)) { headers.Add("diag-script-etag", scriptETag); } if (!string.IsNullOrWhiteSpace(assemblyName)) { headers.Add("diag-assembly-name", assemblyName); } var response = await DiagnosticClient.Execute(method, path, body?.ToString(), internalClient, internalView, headers); if (response != null) { var responseString = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { var responseObject = JsonConvert.DeserializeObject(responseString); if (response.Headers.Contains("diag-script-etag")) { Request.HttpContext.Response.Headers.Add("diag-script-etag", response.Headers.GetValues("diag-script-etag").First()); } if (path.EndsWith("/diagnostics/publish", StringComparison.OrdinalIgnoreCase) && tos.Count > 0 && Env.IsProduction()) { EmailNotificationService.SendPublishingAlert(alias, detectorId, applensLink, tos); } return(Ok(responseObject)); } else if (response.StatusCode == HttpStatusCode.BadRequest) { return(BadRequest(responseString)); } } return(StatusCode((int)response.StatusCode)); }