On an ASP.NET Core 2.2 controller I have the following:
var principal = this.User as ClaimsPrincipal;
var authenticated = this.User.Identity.IsAuthenticated;
var claims = this.User.Identities.FirstOrDefault().Claims;
var id = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
I am able to check if the user is authenticated and gets the claims including id.
How can I do the same outside of the Controller where I do not have this.User?
Inject IHttpContextAccessor interface into the target class. This will give access to the current User via the HttpContext
This provides an opportunity to abstract this feature by creating a service to provide just the information you want (Which is the current logged in user)
public interface IUserService {
ClaimsPrincipal GetUser();
}
public class UserService : IUserService {
private readonly IHttpContextAccessor accessor;
public UserService(IHttpContextAccessor accessor) {
this.accessor = accessor;
}
public ClaimsPrincipal GetUser() {
return accessor?.HttpContext?.User as ClaimsPrincipal;
}
}
You need to setup IHttpContextAccessor now in Startup.ConfigureServices in order to be able to inject it:
services.AddHttpContextAccessor();
services.AddTransient<IUserService, UserService>();
and inject your service where needed.
It's important to note that
HttpContextcould be null. Just because you haveIHttpContextAccessor, doesn't mean that you're going to actually be able to always get theHttpContext. Importantly, the code where you're using this must be within the request pipeline in some way orHttpContextwill be null.
Credit @ChrisPratt via comment
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With