| | | 1 | | using System.Diagnostics; |
| | | 2 | | using System.Security.Claims; |
| | | 3 | | using ProjectTemplate.Infrastructure.Data.Auditing; |
| | | 4 | | |
| | | 5 | | namespace ProjectTemplate.Web.Accessors; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Resolves structured application audit context from the active HTTP request. |
| | | 9 | | /// </summary> |
| | 12 | 10 | | public sealed class HttpContextApplicationAuditContextAccessor( |
| | 12 | 11 | | IHttpContextAccessor httpContextAccessor) |
| | | 12 | | : IApplicationAuditContextAccessor |
| | | 13 | | { |
| | | 14 | | private const string _subjectClaimType = "sub"; |
| | | 15 | | |
| | | 16 | | public ApplicationAuditContext Current |
| | | 17 | | { |
| | | 18 | | get |
| | | 19 | | { |
| | 0 | 20 | | HttpContext? httpContext = httpContextAccessor.HttpContext; |
| | 0 | 21 | | ClaimsPrincipal? user = httpContext?.User; |
| | | 22 | | |
| | 0 | 23 | | string? subject = GetAuthenticatedClaim(user, _subjectClaimType) |
| | 0 | 24 | | ?? GetAuthenticatedClaim(user, ClaimTypes.NameIdentifier); |
| | | 25 | | |
| | 0 | 26 | | if (!string.IsNullOrWhiteSpace(subject)) |
| | | 27 | | { |
| | 0 | 28 | | return new ApplicationAuditContext( |
| | 0 | 29 | | subject, |
| | 0 | 30 | | ApplicationAuditActorTypes.Human, |
| | 0 | 31 | | subject, |
| | 0 | 32 | | correlationId: httpContext?.TraceIdentifier, |
| | 0 | 33 | | traceId: Activity.Current?.TraceId.ToString(), |
| | 0 | 34 | | spanId: Activity.Current?.SpanId.ToString()); |
| | | 35 | | } |
| | | 36 | | |
| | 0 | 37 | | string? remoteIp = httpContext?.Connection.RemoteIpAddress?.ToString(); |
| | | 38 | | |
| | 0 | 39 | | return !string.IsNullOrWhiteSpace(remoteIp) |
| | 0 | 40 | | ? new ApplicationAuditContext( |
| | 0 | 41 | | remoteIp, |
| | 0 | 42 | | ApplicationAuditActorTypes.Network, |
| | 0 | 43 | | $"Remote IP: {remoteIp}", |
| | 0 | 44 | | correlationId: httpContext?.TraceIdentifier, |
| | 0 | 45 | | traceId: Activity.Current?.TraceId.ToString(), |
| | 0 | 46 | | spanId: Activity.Current?.SpanId.ToString()) |
| | 0 | 47 | | : new ApplicationAuditContext( |
| | 0 | 48 | | "Unknown", |
| | 0 | 49 | | ApplicationAuditActorTypes.Unknown, |
| | 0 | 50 | | "Unknown", |
| | 0 | 51 | | correlationId: httpContext?.TraceIdentifier, |
| | 0 | 52 | | traceId: Activity.Current?.TraceId.ToString(), |
| | 0 | 53 | | spanId: Activity.Current?.SpanId.ToString()); |
| | | 54 | | } |
| | | 55 | | } |
| | | 56 | | |
| | | 57 | | private static string? GetAuthenticatedClaim( |
| | | 58 | | ClaimsPrincipal? user, |
| | | 59 | | string claimType) |
| | | 60 | | { |
| | 0 | 61 | | if (user?.Identity?.IsAuthenticated != true) |
| | | 62 | | { |
| | 0 | 63 | | return null; |
| | | 64 | | } |
| | | 65 | | |
| | 0 | 66 | | string? value = user.FindFirst(claimType)?.Value?.Trim(); |
| | 0 | 67 | | return string.IsNullOrWhiteSpace(value) ? null : value; |
| | | 68 | | } |
| | | 69 | | } |