Getting the ClaimsPrincipal in a logic layer in an aspnet core 1 application

I’m writing an aspnet core 1 application.
Using a bearer token authentication I have the User property inside the controller with the correct identity. However I cant seem to find a way to grab with identity as I did before using the ClaimPrincipal.Current static.
What is the current best practice to get this data inside the BL layers with out passing the ClaimPrincipal object around?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Further investigating this issue I’ve found that it is possible to use the native DI container to inject the ClaimsPrincipal where needed like that:

services.AddTransient<ClaimsPrincipal>(s =>
    s.GetService<IHttpContextAccessor>().HttpContext.User);

This feels kind of weird injecting it, however it is better than storing it in the CallContext.

Method 2

Here is better answer for dotnet core 2.0 and newer: https://adamstorr.azurewebsites.net/blog/are-you-registering-ihttpcontextaccessor-correctly

Basically add IHttpContextAccessor to services as Singleton:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddHttpContextAccessor();
}

To consume inject IHttpContextAccessor into your class:

public class YourService : IYourService {
        private readonly IHttpContextAccessor _httpContextAccessor;

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

and access _httpContextAccessor.HttpContext in your methods.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x