joh*_*y 5 5 c# authentication identityserver4 asp.net-core-2.0
我正在试图弄清楚如何使用.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");
}
}
};
});
Run Code Online (Sandbox Code Playgroud)
我有一项服务,我需要登录用户,我无法弄清楚如何获得它.
public interface IAuthenticatedUserManager<T>
where T: class
{
T GetLoggedInUser();
}
public class AuthenticatedUserManager : IAuthenticatedUserManager<User>
{
public User GetLoggedInUser()
{
//HttpContext.Current
}
}
Run Code Online (Sandbox Code Playgroud)
它用于HttpContext.Current,但我不认为它是.Net-Core 2中的一个选项.如何从.Net Core 2中检索我的ClaimsIdentity?
这应该适合你:
var user = (HttpContext.User.Identity as ClaimsIdentity);
Run Code Online (Sandbox Code Playgroud)
然后用户对象有你需要的东西。
我想出了如何做到这一点。因为,我使用的是需要将 HttpContext 注入其中的自定义服务,所以我需要将访问器注册为可注入:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Run Code Online (Sandbox Code Playgroud)
然后在我的身份验证管理器中我可以访问我的 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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1986 次 |
| 最近记录: |