.Net Core IdentityServer4获取经过身份验证的用户

问题描述 投票:5回答:2

我正在试图弄清楚如何使用.Net-Core 2从身份服务器4中检索登录用户。我的身份验证目前正在运行,我只想弄清楚如何从HTTP上下文中检索声明身份。

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

我有一项服务,我需要登录用户,我无法弄清楚如何获得它。

public interface IAuthenticatedUserManager<T>
    where T: class
{
    T GetLoggedInUser();
}

public class AuthenticatedUserManager : IAuthenticatedUserManager<User>
{
    public User GetLoggedInUser()
    { 
        //HttpContext.Current
    }
}

它用于HttpContext.Current,但我不认为它是.Net-Core 2中的一个选项。如何从.Net Core 2中检索我的ClaimsIdentity?

c# authentication asp.net-core-2.0 identityserver4
2个回答
2
投票

这应该适合你:

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

然后用户对象具有您所需的功能。


1
投票

我想出了如何做到这一点。因为,我正在使用需要HttpContext注入的自定义服务,我需要注册一个访问器作为注入:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

然后在我的身份验证管理器中,我可以访问我的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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.