Skip to content

Commit

Permalink
HTTP ResponseStatusCode
Browse files Browse the repository at this point in the history
  • Loading branch information
yoelhor committed Jan 1, 2024
1 parent 44f4ca6 commit 1c4d67c
Show file tree
Hide file tree
Showing 9 changed files with 54 additions and 33 deletions.
2 changes: 1 addition & 1 deletion Areas/oauth2/Controllers/AuthorizeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

}
Expand Down
4 changes: 2 additions & 2 deletions Areas/oauth2/Controllers/OpenIdConfigurationController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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" });
}

Expand Down Expand Up @@ -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);
}
Expand Down
2 changes: 1 addition & 1 deletion Areas/oauth2/Controllers/OpenIdKeysController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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" });
}

Expand Down
4 changes: 2 additions & 2 deletions Areas/oauth2/Controllers/TokenController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public async Task<IActionResult> 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." }));

Check warning on line 46 in Areas/oauth2/Controllers/TokenController.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.
return BadRequest(new { error = "GET request is not allowed." });
}

Expand Down Expand Up @@ -141,7 +141,7 @@ private async Task<IActionResult> 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);
}
Expand Down
2 changes: 1 addition & 1 deletion Areas/oauth2/Controllers/UserInfoController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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));

Check warning on line 75 in Areas/oauth2/Controllers/UserInfoController.cs

View workflow job for this annotation

GitHub Actions / build

Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

Check warning on line 75 in Areas/oauth2/Controllers/UserInfoController.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.

return Ok(payload);
}
Expand Down
10 changes: 6 additions & 4 deletions Areas/proxy/Controllers/OpenIdConfigurationController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ public OpenIdConfigurationController(ILogger<OpenIdConfigurationController> logg
[ActionName("invoke")]
public async Task<IActionResult> IndexGetAsync(string tenantId, string id)
{
HttpResponseMessage response = null;

// Get the tenant settings
SettingsEntity settings = _settingsService.GetConfig(tenantId);

Expand All @@ -44,12 +46,12 @@ public async Task<IActionResult> 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();
Expand All @@ -60,13 +62,13 @@ public async Task<IActionResult> 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 });
}
}
Expand Down
15 changes: 9 additions & 6 deletions Areas/proxy/Controllers/TokenController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,31 +37,34 @@ public TokenController(ILogger<TokenController> logger, TelemetryClient telemetr
[ActionName("invoke")]
public async Task<IActionResult> 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 });
}

Expand Down
11 changes: 6 additions & 5 deletions Areas/proxy/Controllers/UserInfoController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,31 +37,32 @@ public UserInfoController(ILogger<UserInfoController> logger, TelemetryClient te
[ActionName("invoke")]
public async Task<IActionResult> 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 });
}
}
Expand Down
37 changes: 26 additions & 11 deletions Commons.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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,

Check warning on line 80 in Commons.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.
string? responseBody = null,
string? additionalData = null)
{
if (string.IsNullOrEmpty(settings.InstrumentationKey))
Expand All @@ -91,8 +93,8 @@ public static async Task LogRequestAsync(HttpRequest Request,

Dictionary<string, string> log = new Dictionary<string, string>();

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
Expand All @@ -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
Expand All @@ -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);
}
}
}
Expand All @@ -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))
Expand All @@ -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)

Check warning on line 154 in Commons.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.
{
if (string.IsNullOrEmpty(settings.InstrumentationKey))
{
Expand All @@ -153,10 +161,17 @@ public static void LogError(HttpRequest Request, TelemetryClient telemetry, Sett
telemetry.InstrumentationKey = settings.InstrumentationKey;

Dictionary<string, string> log = new Dictionary<string, string>();
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();
}
Expand Down

0 comments on commit 1c4d67c

Please sign in to comment.