Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Core IdentityServer4 Get Authenticated User

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?

like image 521
johnny 5 Avatar asked Jan 03 '18 18:01

johnny 5


2 Answers

This should work for you:

var user = (HttpContext.User.Identity as ClaimsIdentity);

And then the user object has what you need.

like image 93
m3n7alsnak3 Avatar answered Sep 20 '22 02:09

m3n7alsnak3


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);
    }
}
like image 36
johnny 5 Avatar answered Sep 21 '22 02:09

johnny 5