ASP.NET Core Web API - How to use User.Claims in service layer

Cenk 1,031 Reputation points
2022-12-27T18:10:27.367+00:00

Hello,

How can I use user claims in the service layer of my application? I can use it as follows in the controller but is there a way to use it in the service layer?

var userId = User.Claims.FirstOrDefault(x => x.Type == "UserId")?.Value;  

...

public class PalasServices : IPalasServices, IDisposable  
    {  
        private readonly UnitOfWork _unitOfWork;  
        private readonly IMapper _mapper;  
        private readonly IConfiguration _configuration;  
  
        public PalasServices(UnitOfWork unitOfWork, IMapper mapper, IConfiguration configuration)  
        {  
            _unitOfWork = unitOfWork;  
            _mapper = mapper;  
            _configuration = configuration;  
        }  
...  
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,815 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 33,191 Reputation points Microsoft External Staff
    2022-12-28T02:38:17.103+00:00

    Hi @Cenk ,

    To access the HttpContext.User's claims from the service, you can try to use AddHttpContextAccessor service and IHttpContextAccessor.

    In your application, register the AddHttpContextAccessor services in the Program.cs or Startup.cs file:

    builder.Services.AddHttpContextAccessor();  
    builder.Services.AddScoped<IPalasServices, PalasServices>();  
    

    Then in the PalasServices service, refer to the following code to inject the IHttpContextAccessor, and then get the user claims:

    public class PalasServices : IPalasServices   
    {  
        private readonly IHttpContextAccessor _http;  
        public PalasServices(IHttpContextAccessor http)  
        {  
            _http = http;  
        }  
        public string GetCurrentUser()  
        {  
            return _http.HttpContext.User.Claims?.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value;  
        }   
    }  
    

    The output as below:

    274407-image.png

    More detail information, see Access HttpContext in ASP.NET Core.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    2 people found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.