Created
February 6, 2023 10:55
-
-
Save jeangatto/66966aa738c034bc81c51377a047fc4b to your computer and use it in GitHub Desktop.
ASP.NET Core Get Current User Provider
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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