Aspnetcore: Injecting ClaimsPrincipal in service layer

Created on 15 Nov 2015  路  2Comments  路  Source: dotnet/aspnetcore

Is there a clean way to get ClaimPrincipal or IIdentity from DI? So it can be used in service layers.
This was ugly, but possible with the "good old" HttpContext.Current.User :smile:

Most helpful comment

You can use the IHttpContextAccessor in your services. If you only care about the user I'd suggest wrapping that in another service IUserAccessor or something.

C# public class UserAccessor : IUserAccessor { private IHttpContextAccessor _accessor; public UserAccessor(IHttpContextAccessor accessor) { _accessor = accessor; } public ClaimsPrincipal User => _accessor. HttpContext.User; }

All 2 comments

You can use the IHttpContextAccessor in your services. If you only care about the user I'd suggest wrapping that in another service IUserAccessor or something.

C# public class UserAccessor : IUserAccessor { private IHttpContextAccessor _accessor; public UserAccessor(IHttpContextAccessor accessor) { _accessor = accessor; } public ClaimsPrincipal User => _accessor. HttpContext.User; }

Ye, I guess that's doable, thx.

Was this page helpful?
0 / 5 - 0 ratings