I'm trying to figure out how to retrieve a logged in user from Identity server 4 using .Net-Core 2. My authentication is working currently, I'm just trying to figure out how I can retrieve the claims Identity from the HTTP Context.
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
}).AddIdentityServerAuthentication(o =>
{
o.Authority = IDP_AUTHORITY_URL;
o.RequireHttpsMetadata = false;
o.ApiName = API_ID;
o.JwtBearerEvents = new JwtBearerEvents
{
OnTokenValidated = async tokenValidationContext =>
{
var claimsIdentity = tokenValidationContext.Principal.Identity as ClaimsIdentity;
if (claimsIdentity == null)
{
return;
}
string userId = claimsIdentity.Claims.FirstOrDefault(c => c.Type == "sub").Value;
if (string.IsNullOrEmpty(userId))
{
throw new AuthenticationException("Error obtaining Subject claim");
}
}
};
});
I have a service which I require the logged in user I can't figure out how to get it.
public interface IAuthenticatedUserManager<T>
where T: class
{
T GetLoggedInUser();
}
public class AuthenticatedUserManager : IAuthenticatedUserManager<User>
{
public User GetLoggedInUser()
{
//HttpContext.Current
}
}
It use to be on the HttpContext.Current, but I do not see that as an option in .Net-Core 2. How can I retreive my ClaimsIdentity from .Net Core 2?
This should work for you:
var user = (HttpContext.User.Identity as ClaimsIdentity);
And then the user object has what you need.
I figured out how to do this. Since, I am using a custom service which needs the HttpContext Injected into it I needed to register an accessor as injectable:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Then in my Authentication Manager I can Access my HttpContext
public class UserAuthenticationManager : IUserAuthenticationManager
{
HttpContext _httpContext;
public UserAuthenticationManager(IHttpContextAccessor httpContextAccessor)
{
this._httpContext = httpContextAccessor?.HttpContext;
}
public ClaimsIdentity GetClaimsIdentity()
{
return (this._httpContext.User.Identity as ClaimsIdentity);
}
}
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