.Net Core IdentityServer4 Get Authenticated User

自作多情 提交于 2019-12-07 04:20:42

问题


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?


回答1:


This should work for you:

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

And then the user object has what you need.




回答2:


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);
    }
}


来源:https://stackoverflow.com/questions/48083148/net-core-identityserver4-get-authenticated-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!