feat: improve logging
All checks were successful
.NET Test Pipeline / build-and-test (push) Successful in 1m12s
Build and Deploy Docker Container / build-and-deploy (push) Successful in 2m11s

This commit is contained in:
2024-12-23 07:48:28 +03:00
parent 053f01eec1
commit 5ff8744a55
3 changed files with 26 additions and 20 deletions

View File

@ -110,21 +110,25 @@ public class OAuthService(ILogger<OAuthService> logger, Dictionary<OAuthProvider
{
var (clientId, _) = providers[provider];
var requestInfo = new RequestContextInfo(context, cookieOptions);
var state = GetHmacString(requestInfo, secretKey);
var redirectUrl = $"?client_id={clientId}" +
"&response_type=code" +
$"&redirect_uri={redirectUri}" +
$"&scope={ProviderData[provider].Scope}" +
$"&state={GetHmacString(new RequestContextInfo(context, cookieOptions), secretKey)}_{Enum.GetName(provider)}";
$"&state={state}_{Enum.GetName(provider)}";
logger.LogInformation("Redirecting user Fingerprint: {Fingerprint} to OAuth provider {Provider} with state: {State}",
requestInfo.Fingerprint,
provider,
state);
return new Uri(ProviderData[provider].RedirectUrl + redirectUrl);
}
public (OAuthProvider Provider, Uri Redirect)[] GetAvailableProviders(string redirectUri)
{
return [.. providers.Select(x => (x.Key, new Uri(redirectUri.TrimEnd('/') + "/?provider=" + (int)x.Key)))];
}
public (OAuthProvider Provider, Uri Redirect)[] GetAvailableProviders(string redirectUri) =>
[.. providers.Select(x => (x.Key, new Uri(redirectUri.TrimEnd('/') + "/?provider=" + (int)x.Key)))];
public async Task<(OAuthProvider provider, OAuthUser User)> LoginOAuth(HttpContext context, CookieOptionsParameters cookieOptions, string redirectUrl, string code, string state, CancellationToken cancellation = default)
{
@ -139,11 +143,17 @@ public class OAuthService(ILogger<OAuthService> logger, Dictionary<OAuthProvider
}
var secretStateData = string.Join("_", partsState.SkipLast(1));
var secretData = GetHmacString(new RequestContextInfo(context, cookieOptions), secretKey);
var requestInfo = new RequestContextInfo(context, cookieOptions);
var secretData = GetHmacString(requestInfo, secretKey);
if (secretData != secretStateData)
{
logger.LogWarning("Fingerprint mismatch. Possible CSRF attack detected.");
logger.LogWarning(
"Fingerprint mismatch. Possible CSRF attack detected. Fingerprint: {Fingerprint}, State: {State}, ExpectedState: {ExpectedState}",
requestInfo.Fingerprint,
secretData,
secretStateData
);
throw new SecurityException("Suspicious activity detected. Please try again.");
}
@ -154,7 +164,7 @@ public class OAuthService(ILogger<OAuthService> logger, Dictionary<OAuthProvider
}
catch (Exception ex)
{
logger.LogWarning(ex, "Failed to exchange authorization code for tokens with provider {Provider}", provider);
logger.LogWarning(ex, "Failed to exchange code for access token with provider {Provider}. State: {State}", provider, state);
}
if (accessToken == null)