From 1c4d67c7897f0ddc4fbf83247e06c4486290de49 Mon Sep 17 00:00:00 2001 From: Yoel Horvitz Date: Mon, 1 Jan 2024 13:40:48 +0200 Subject: [PATCH] HTTP ResponseStatusCode --- .../oauth2/Controllers/AuthorizeController.cs | 2 +- .../OpenIdConfigurationController.cs | 4 +- .../Controllers/OpenIdKeysController.cs | 2 +- Areas/oauth2/Controllers/TokenController.cs | 4 +- .../oauth2/Controllers/UserInfoController.cs | 2 +- .../OpenIdConfigurationController.cs | 10 +++-- Areas/proxy/Controllers/TokenController.cs | 15 +++++--- Areas/proxy/Controllers/UserInfoController.cs | 11 +++--- Commons.cs | 37 +++++++++++++------ 9 files changed, 54 insertions(+), 33 deletions(-) diff --git a/Areas/oauth2/Controllers/AuthorizeController.cs b/Areas/oauth2/Controllers/AuthorizeController.cs index 4823b5d..09272e1 100644 --- a/Areas/oauth2/Controllers/AuthorizeController.cs +++ b/Areas/oauth2/Controllers/AuthorizeController.cs @@ -69,7 +69,7 @@ public RedirectResult SignIn(string tenantId, string email, string password, str if (client_id == "default") URL = URL + $"&id_token={id_token}"; - Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT, URL); + Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT, null, URL); return Redirect(URL); } diff --git a/Areas/oauth2/Controllers/OpenIdConfigurationController.cs b/Areas/oauth2/Controllers/OpenIdConfigurationController.cs index 81b15a0..62ddf00 100644 --- a/Areas/oauth2/Controllers/OpenIdConfigurationController.cs +++ b/Areas/oauth2/Controllers/OpenIdConfigurationController.cs @@ -42,7 +42,7 @@ public IActionResult Index(string tenantId) // Check if service availble if (!settings.GetOAuth2Settings().OpenIdConfiguration.Enabled) { - Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT, JsonSerializer.Serialize(new { error = "Service unavailable" })); + Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT, null, null, JsonSerializer.Serialize(new { error = "Service unavailable" })); return BadRequest(new { error = "Service unavailable" }); } @@ -72,7 +72,7 @@ public IActionResult Index(string tenantId) IdTokenSigningAlgValuesSupported = new[] { OpenIdConfigurationController.SigningCredentials.Value.Algorithm } }; - Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT, JsonSerializer.Serialize(payload)); + Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT, null, JsonSerializer.Serialize(payload)); return Ok(payload); } diff --git a/Areas/oauth2/Controllers/OpenIdKeysController.cs b/Areas/oauth2/Controllers/OpenIdKeysController.cs index 1849ecd..867bbe1 100644 --- a/Areas/oauth2/Controllers/OpenIdKeysController.cs +++ b/Areas/oauth2/Controllers/OpenIdKeysController.cs @@ -42,7 +42,7 @@ public ActionResult Index(string tenantId) // Check if service availble if (!settings.GetOAuth2Settings().JWKs.Enabled) { - Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT, JsonSerializer.Serialize(new { error = "Service unavailable" })); + Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT, null, JsonSerializer.Serialize(new { error = "Service unavailable" })); return BadRequest(new { error = "Service unavailable" }); } diff --git a/Areas/oauth2/Controllers/TokenController.cs b/Areas/oauth2/Controllers/TokenController.cs index 51d2537..5c06272 100644 --- a/Areas/oauth2/Controllers/TokenController.cs +++ b/Areas/oauth2/Controllers/TokenController.cs @@ -43,7 +43,7 @@ public async Task IndexAsyncGet(string tenantId, string code) // Check if HTTP GET is allowed if (!settings.GetOAuth2Settings().Token.HttpMethods.GET) { - await Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT, JsonSerializer.Serialize(new { error = "GET request is not allowed." })); + await Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT, null, JsonSerializer.Serialize(new { error = "GET request is not allowed." })); return BadRequest(new { error = "GET request is not allowed." }); } @@ -141,7 +141,7 @@ private async Task IndexCommonAsync(string tenantId, string code) tenantId = tenantId }; - await Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT, JsonSerializer.Serialize(payload)); + await Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT, null, JsonSerializer.Serialize(payload)); return new OkObjectResult(payload); } diff --git a/Areas/oauth2/Controllers/UserInfoController.cs b/Areas/oauth2/Controllers/UserInfoController.cs index 447243b..aa67dea 100644 --- a/Areas/oauth2/Controllers/UserInfoController.cs +++ b/Areas/oauth2/Controllers/UserInfoController.cs @@ -72,7 +72,7 @@ public IActionResult Index(string tenantId) payload.Add(item.Type, item.Value); } - Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT, JsonSerializer.Serialize(payload)); + Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT, null, JsonSerializer.Serialize(payload)); return Ok(payload); } diff --git a/Areas/proxy/Controllers/OpenIdConfigurationController.cs b/Areas/proxy/Controllers/OpenIdConfigurationController.cs index 1d3b7a1..1281842 100644 --- a/Areas/proxy/Controllers/OpenIdConfigurationController.cs +++ b/Areas/proxy/Controllers/OpenIdConfigurationController.cs @@ -36,6 +36,8 @@ public OpenIdConfigurationController(ILogger logg [ActionName("invoke")] public async Task IndexGetAsync(string tenantId, string id) { + HttpResponseMessage response = null; + // Get the tenant settings SettingsEntity settings = _settingsService.GetConfig(tenantId); @@ -44,12 +46,12 @@ public async Task IndexGetAsync(string tenantId, string id) // Check if HTTP GET is allowed if (string.IsNullOrEmpty(id)) { - await Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT, JsonSerializer.Serialize(new { error = "Target token URL is not configured." })); + await Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT, null, JsonSerializer.Serialize(new { error = "Target token URL is not configured." })); return BadRequest(new { error = "Cannot find the target identity provider well known configuration endpoint." }); } try { - HttpResponseMessage response = await CallIdentityProviderAsync(tenantId, Uri.UnescapeDataString(id)); + response = await CallIdentityProviderAsync(tenantId, Uri.UnescapeDataString(id)); // Read the input claims from the response body string body = await response.Content.ReadAsStringAsync(); @@ -60,13 +62,13 @@ public async Task IndexGetAsync(string tenantId, string id) payload.TokenEndpoint = Url.ActionLink("Invoke", "Token", new { Area = "proxy", tenantId = tenantId }) + "/" + HttpRequestHelper.Base64Encode(payload.TokenEndpoint); payload.UserInfoEndpoint = Url.ActionLink("Invoke", "UserInfo", new { Area = "proxy", tenantId = tenantId }) + "/" + HttpRequestHelper.Base64Encode(payload.UserInfoEndpoint); - Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT + "End", JsonSerializer.Serialize(payload)).Wait(); + Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT + "End", response, JsonSerializer.Serialize(payload)).Wait(); return Ok(payload); } catch (System.Exception ex) { - Commons.LogError(Request, _telemetry, settings, tenantId, EVENT + "Error", ex.Message); + Commons.LogError(Request, _telemetry, settings, tenantId, EVENT + "Error", ex.Message, response); return BadRequest(new { error = ex.Message }); } } diff --git a/Areas/proxy/Controllers/TokenController.cs b/Areas/proxy/Controllers/TokenController.cs index c63a064..a66b530 100644 --- a/Areas/proxy/Controllers/TokenController.cs +++ b/Areas/proxy/Controllers/TokenController.cs @@ -37,31 +37,34 @@ public TokenController(ILogger logger, TelemetryClient telemetr [ActionName("invoke")] public async Task IndexGetAsync(string tenantId, string id) { + HttpResponseMessage response = null; + // Get the tenant settings SettingsEntity settings = _settingsService.GetConfig(tenantId); - Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT + "Start", null, JsonSerializer.Serialize(new { Action = "Start reverse proxy", URL = id })).Wait(); + Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT + "Start", null, null, JsonSerializer.Serialize(new { Action = "Start reverse proxy", URL = id })).Wait(); - // Check if HTTP GET is allowed + // Check if the custom IDP tenant ID exists if (string.IsNullOrEmpty(id)) { - await Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT, JsonSerializer.Serialize(new { error = "Target token URL is not configured." })); + await Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT, null, JsonSerializer.Serialize(new { error = "Target token URL is not configured." })); return BadRequest(new { error = "Cannot find the target identity provider token endpoint." }); } + try { - HttpResponseMessage response = await CallIdentityProviderAsync(tenantId, id); + response = await CallIdentityProviderAsync(tenantId, id); // Read the input claims from the response body string body = await response.Content.ReadAsStringAsync(); - Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT + "End", body).Wait(); + Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT + "End", response, body).Wait(); return new HttpResponseMessageResult(response); } catch (System.Exception ex) { - Commons.LogError(Request, _telemetry, settings, tenantId, EVENT + "Error", ex.Message); + Commons.LogError(Request, _telemetry, settings, tenantId, EVENT + "Error", ex.Message, response); return BadRequest(new { error = ex.Message }); } diff --git a/Areas/proxy/Controllers/UserInfoController.cs b/Areas/proxy/Controllers/UserInfoController.cs index 9b1793d..22fe976 100644 --- a/Areas/proxy/Controllers/UserInfoController.cs +++ b/Areas/proxy/Controllers/UserInfoController.cs @@ -37,31 +37,32 @@ public UserInfoController(ILogger logger, TelemetryClient te [ActionName("invoke")] public async Task IndexGetAsync(string tenantId, string id) { + HttpResponseMessage response = null; // Get the tenant settings SettingsEntity settings = _settingsService.GetConfig(tenantId); - Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT + "Start", null, JsonSerializer.Serialize(new { Action = "Start reverse proxy", URL = id })).Wait(); + Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT + "Start", null, null, JsonSerializer.Serialize(new { Action = "Start reverse proxy", URL = id })).Wait(); // Check if HTTP GET is allowed if (string.IsNullOrEmpty(id)) { - await Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT, JsonSerializer.Serialize(new { error = "Target token URL is not configured." })); + await Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT, null, JsonSerializer.Serialize(new { error = "Target token URL is not configured." })); return BadRequest(new { error = "Cannot find the target identity provider token endpoint." }); } try { - HttpResponseMessage response = await CallIdentityProviderAsync(tenantId, Uri.UnescapeDataString(id)); + response = await CallIdentityProviderAsync(tenantId, Uri.UnescapeDataString(id)); // Read the input claims from the response body string body = await response.Content.ReadAsStringAsync(); - Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT + "End", body).Wait(); + Commons.LogRequestAsync(Request, _telemetry, settings, tenantId, EVENT + "End", response, body).Wait(); return new HttpResponseMessageResult(response); } catch (System.Exception ex) { - Commons.LogError(Request, _telemetry, settings, tenantId, EVENT + "Error", ex.Message); + Commons.LogError(Request, _telemetry, settings, tenantId, EVENT + "Error", ex.Message, response); return BadRequest(new { error = ex.Message }); } } diff --git a/Commons.cs b/Commons.cs index 8fb51f0..d562858 100644 --- a/Commons.cs +++ b/Commons.cs @@ -71,12 +71,14 @@ public static string BuildJwtToken(X509SigningCredentials SigningCredentials, Ht return jwtHandler.WriteToken(token); } - public static async Task LogRequestAsync(HttpRequest Request, + public static async Task LogRequestAsync( + HttpRequest Request, TelemetryClient telemetry, SettingsEntity settings, string tenantId, string page, - string? response = null, + HttpResponseMessage Response = null, + string? responseBody = null, string? additionalData = null) { if (string.IsNullOrEmpty(settings.InstrumentationKey)) @@ -91,8 +93,8 @@ public static async Task LogRequestAsync(HttpRequest Request, Dictionary log = new Dictionary(); - log.Add("Method", Request.Method); - log.Add("URL", $"{Request.Scheme}://{Request.Host}{Request.Path}{Request.QueryString}"); + log.Add("RequestMethod", Request.Method); + log.Add("RequestURL", $"{Request.Scheme}://{Request.Host}{Request.Path}{Request.QueryString}"); log.Add("TenantId", tenantId); // Get the target URL @@ -105,7 +107,7 @@ public static async Task LogRequestAsync(HttpRequest Request, // Request headers string headers = JsonSerializer.Serialize(Request.Headers); - log.Add("Headers", headers); + log.Add("RequestHeaders", headers); // Request body try @@ -116,7 +118,7 @@ public static async Task LogRequestAsync(HttpRequest Request, using (StreamReader stream = new StreamReader(Request.Body)) { body = await stream.ReadToEndAsync(); - log.Add("Body", body); + log.Add("RequestBody", body); } } } @@ -129,10 +131,16 @@ public static async Task LogRequestAsync(HttpRequest Request, throw; } + // Response body + if (Response != null) + { + log.Add("ResponseStatusCode", Response.StatusCode.ToString()); + } - if (!string.IsNullOrEmpty(response)) + // Response body + if (!string.IsNullOrEmpty(responseBody)) { - log.Add("Response", response); + log.Add("ResponseBody", responseBody); } if (!string.IsNullOrEmpty(additionalData)) @@ -143,7 +151,7 @@ public static async Task LogRequestAsync(HttpRequest Request, telemetry.TrackEvent($"{tenantId}_{page}", log); telemetry.Flush(); } - public static void LogError(HttpRequest Request, TelemetryClient telemetry, SettingsEntity settings, string tenantId, string page, string error) + public static void LogError(HttpRequest Request, TelemetryClient telemetry, SettingsEntity settings, string tenantId, string page, string error, HttpResponseMessage Response = null) { if (string.IsNullOrEmpty(settings.InstrumentationKey)) { @@ -153,10 +161,17 @@ public static void LogError(HttpRequest Request, TelemetryClient telemetry, Sett telemetry.InstrumentationKey = settings.InstrumentationKey; Dictionary log = new Dictionary(); - log.Add("Method", Request.Method); - log.Add("URL", $"{Request.Scheme}://{Request.Host}{Request.Path}{Request.QueryString}"); + log.Add("RequestMethod", Request.Method); + log.Add("RequestURL", $"{Request.Scheme}://{Request.Host}{Request.Path}{Request.QueryString}"); log.Add("Error", error); log.Add("TenantId", tenantId); + + // Response body + if (Response != null) + { + log.Add("ResponseStatusCode", Response.StatusCode.ToString()); + } + telemetry.TrackEvent($"{tenantId}_{page}", log); telemetry.Flush(); }