11
votes

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.

1
Why not just inject IHttpContextAccessor into the dependent classes and extract he user from the context as needed.Nkosi
@Nkosi because I just want the current user, and his claims. not the entire http context.Justin Dearing

1 Answers

9
votes

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.