我正在尝试弄清楚如何使用.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?
答案 0 :(得分:2)
这应该适合你:
var user = (HttpContext.User.Identity as ClaimsIdentity);
然后用户对象就可以满足您的需求。
答案 1 :(得分: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);
}
}