Skip to content

Instantly share code, notes, and snippets.

@jeangatto
Created February 6, 2023 10:55
Show Gist options
  • Save jeangatto/66966aa738c034bc81c51377a047fc4b to your computer and use it in GitHub Desktop.
Save jeangatto/66966aa738c034bc81c51377a047fc4b to your computer and use it in GitHub Desktop.
ASP.NET Core Get Current User Provider
public interface ICurrentUserProvider
{
Guid? GetCurrentUserId();
}
public class CurrentUserProvider : ICurrentUserProvider
{
private readonly IHttpContextAccessor _httpContextAcessor;
public CurrentUserProvider(IHttpContextAccessor httpContextAcessor)
=> _httpContextAcessor = httpContextAcessor;
public Guid? GetCurrentUserId()
{
if (_httpContextAcessor.HttpContext?.User?.Identity?.IsAuthenticated == true)
{
var claimValue = _httpContextAcessor?.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier);
return claimValue != null && Guid.TryParse(claimValue, out var userId) ? userId : default;
}
return default;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment