.Net Core IdentityServer4获取经过身份验证的用户
我正在尝试找出如何使用.Net-Core 2从Identity Server 4检索登录用户.我的身份验证当前正在起作用,我只是在尝试找出如何从中检索声明Identity的方法. HTTP上下文.
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
}
}
它曾经位于HttpContext.Current上,但是在.Net-Core 2中我不认为它是一个选项.如何从.Net Core 2中撤回我的ClaimsIdentity?
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?
我知道了如何做到这一点.因为,我正在使用需要将HttpContext注入其中的自定义服务,所以我需要将访问器注册为可注入的:
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>();
然后在我的身份验证管理器中,我可以访问我的HttpContext
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);
}
}