47 lines
1.6 KiB
C#
47 lines
1.6 KiB
C#
using System.Security.Claims;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.IdentityModel.JsonWebTokens;
|
|
using mws.backend.dotnet.application.Common;
|
|
|
|
namespace mws.backend.dotnet.api.Authentication;
|
|
|
|
public class HttpCurrentUser(IHttpContextAccessor accessor) : ICurrentUser
|
|
{
|
|
public Guid? UserId
|
|
{
|
|
get
|
|
{
|
|
var value = accessor.HttpContext?.User.FindFirstValue(JwtRegisteredClaimNames.Sub)
|
|
?? accessor.HttpContext?.User.FindFirstValue(ClaimTypes.NameIdentifier)
|
|
?? accessor.HttpContext?.User.FindFirstValue("sub");
|
|
return value is not null && Guid.TryParse(value, out var id) ? id : null;
|
|
}
|
|
}
|
|
|
|
public string? Username =>
|
|
accessor.HttpContext?.User.FindFirstValue(ClaimTypes.Name)
|
|
?? accessor.HttpContext?.User.FindFirstValue("name");
|
|
|
|
public string? IpAddress
|
|
{
|
|
get
|
|
{
|
|
var context = accessor.HttpContext;
|
|
if (context is null) return null;
|
|
var forwarded = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
|
|
if (!string.IsNullOrWhiteSpace(forwarded))
|
|
{
|
|
var first = forwarded.Split(',')[0].Trim();
|
|
if (first.Length > 0) return Truncate(first, 45);
|
|
}
|
|
return Truncate(context.Connection.RemoteIpAddress?.ToString(), 45);
|
|
}
|
|
}
|
|
|
|
public string? UserAgent =>
|
|
Truncate(accessor.HttpContext?.Request.Headers.UserAgent.ToString(), 512);
|
|
|
|
private static string? Truncate(string? value, int max) =>
|
|
string.IsNullOrEmpty(value) ? value : (value.Length <= max ? value : value[..max]);
|
|
}
|