Menu

Asp.net Core – User Accessor service to retrieve the current user from the HttpContext

Regardless of authentication mechanism, you communicate with your API/MVC, you will need to retrieve the user you are dealing with to return appropriate data aligned to that user. Since I am into JWT Bearer Authentication (these days), I have written service that gets injected into my Controler/Feature.

Interface

    public interface ICurrentUserAccessor
    {
        string GetCurrentUsername();
        string GetCurrentRole();        
    }

Implementation

    public class CurrentUserAccessor : ICurrentUserAccessor
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public CurrentUserAccessor(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public string GetCurrentUsername()
        {
            return _httpContextAccessor.HttpContext.User?.Claims?.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value;
        }

        public string GetCurrentRole()
        {
            return _httpContextAccessor.HttpContext.User?.Claims?.FirstOrDefault(x => x.Type == ClaimTypes.Role)?.Value;
        }
    }

I know these are basic things but it will help you lot of time if you had it documented, Enjoy

Leave a comment