Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the ClaimsPrincipal or ClaimsIdentity from inside ASP.NET Core dependency Injection

I have a class that has ClaimsIdentity as a dependency like so:

public ClaimsIdentityDecorator(ClaimsIdentity identity)

That is supposed to be the Claimsidentity of the current user. I retrieve it like via the IHttpContextAccessor like so:

services.AddScoped( x=>
{
    var context =  x.GetService<IHttpContextAccessor>();
    return context.HttpContext.User.Identity as ClaimsIdentity;
});

I need to inspect a users claims, and it would seem that ClaimsIdentity or ClaimsPrincipal or some other identity object would be automatically injected for me. Retrieving it from the HttpContext and adding it myself is fine. However, if there is another object or interface that has claims on it that's already there, I would like to design my classes to take that dependency.

Also, I just want to make sure this should be injected at the Scope level.

like image 845
Justin Dearing Avatar asked Nov 08 '17 16:11

Justin Dearing


People also ask

What is ClaimsPrincipal in .NET Core?

ClaimsPrincipal exposes a collection of identities, each of which is a ClaimsIdentity. In the common case, this collection, which is accessed through the Identities property, will only have a single element. The introduction of ClaimsPrincipal in .

How do I apply a claim in .NET Core?

Adding claims checks Claim based authorization checks are declarative - the developer embeds them within their code, against a controller or an action within a controller, specifying claims which the current user must possess, and optionally the value the claim must hold to access the requested resource.


1 Answers

There's no built in way to provide a ClaimsIdentity that I'm aware of, but you probably want AddTransient. If a user logs out, but the instance was created at the beginning of the request AddScoped won't reflect that change.

like image 95
Charles Avatar answered Oct 04 '22 04:10

Charles