Home > front end >  How can I access ClaimsPrincipal from a static class?
How can I access ClaimsPrincipal from a static class?

Time:10-02

In my HomeController I can perfectly access the ClaimsPrincipal, however using a static class it doesn't seem to be possible. How can I retrieve the ClaimsHelper?

public static class ClaimsHelper
{
    public static List<Claim> GetCurrentUser()
    {
        return System.Security.Claims.ClaimsPrincipal.Current.Claims.ToList();
    }
}

CodePudding user response:

You can write an extension method for your need and use it in your actions

public static class HttpContextExtensions
{


    public static ClaimsPrincipal GetClaims(this HttpContext httpContext)
    {
        var principal = httpContext.User as ClaimsPrincipal;
        return principal;
    }

}

and then use it in your actions:

[HttpGet]
public IActionResult Index ()
{
    var user = HttpContext.GetClaimsPrincipal();

    return Ok(user);
}

or you can use another way like this:

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

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

or another way using DI just add IHttpContextAccessor then inject it to your helper class then register your helper class as a singleton service.

CodePudding user response:

Though what the answer above does will work, I am not sure it's handling the use case you want. It seems you just need to have a variable in the static class that is the httpcontext. Then you can access it like you would anywhere else. Note, this is generally a poor pattern filled with landmines since you could be passing the context all over the place, but it does work. This should do it, but I have not yet tested.

public static class ClaimsHelper
{
    public static List<Claim> GetCurrentUser(HttpContext context)
    {
        return context.User.Claims.ToList();
    }
}

Inside a controller, you would call it like this:

public IActionResult Index ()
{
    var ctx = HttpContext.Current;
    var claims = ClaimsHelper.GetCurrentUser(ctx);
    ...
}
  • Related