【发布时间】:2018-06-19 21:12:46
【问题描述】:
在 ASP.NET Core 2.1 应用程序中使用 Windows 身份验证。在数据库中,我们有一个User 表,用于存储用户及其 Sid。它与 UserProfile 具有 1-1 关系,其中包含我想用于声明的信息。
我为索赔转换添加了此服务:
public class UserStatusClaimsTransformation : IClaimsTransformation
{
private readonly MyDbContext _context;
public UserStatusClaimsTransformation(MyDbContext context)
{
_context = context;
}
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
if (principal.Identity is WindowsIdentity identity)
{
User user = await _context.User
.Include(u => u.UserProfile)
.Where(u => new SecurityIdentifier(u.WindowsSid, 0) == identity.User)
.SingleOrDefaultAsync();
if (user != null)
{
identity.AddClaim(new Claim("Status", user.UserProfile));
}
}
return principal;
}
}
我的问题是,一旦注册了此服务,在管道中其他地方访问的 IPrincipal 现在是 ClaimsPrincipal 而不是 WindowsPrincipal。例如,在 MyDbContext 中,我通过 DI 注入 IPrincipal:
public MyDbContext(DbContextOptions<MyDbContext> options, IPrincipal principal) : base(options)
{
_principal = principal;
}
以前,这是 WindowsPrincipal,我可以从 _principal.Identity.Name 获取用户名,但在注册我的 Claims Transformer 后,它是 ClaimsPrincipal,而 _principal.Identity.Name 为空。在使用声明转换后,有没有办法将通过 DI 提供的 IPrincipal 保留为 WindowsPrincipal?
【问题讨论】:
标签: c# asp.net-core windows-authentication claims-based-identity