Asp.Net核心|扩展Windows身份验证对象

时间:2018-06-26 16:05:28

标签: c# asp.net-core windows-authentication asp.net-core-identity

我想在我的Intranet应用程序中使用for(;dx > 0; dx--){result.append('EAST');} for(;dx < 0; dx++){result.append('WEST');} for(;dy > 0; dy--){result.append('NORTH');} for(;dy < 0; dy++){result.append('SOUTH');} ,但是我需要扩展身份对象以获得一些额外的数据。到目前为止,我只能访问身份用户中的域名。我试图实现自己的用户/角色存储,以拦截授权调用,然后使用域名访问我们的数据库并获取额外的数据。我实现了自己的商店,但似乎没有一个方法被调用。当应用程序授权窗口用户时,我该如何拦截,以便我可以进入数据库并获取需要放入用户对象中的内容?

这是我的Startup.cs

Windows Auth

1 个答案:

答案 0 :(得分:0)

我所做的是从MVC中删除基本身份验证,并添加了AuthenticationHandler,它扩展了AuthenticationService,因为我不想从IAuthenticationService中重新发明每个方法,所以:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddIdentity<MyUser, IdentityRole>()
     .AddUserStore<MyUserStore>()
     .AddRoleStore<MyRoleStore>()
     .AddDefaultTokenProviders();

services.Remove(services.FirstOrDefault(x => x.ServiceType == typeof(IAuthenticationService)));
services.Add(new ServiceDescriptor(typeof(IAuthenticationService),typeof(AuthenticationHandler), ServiceLifetime.Scoped));

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

然后

public class AuthenticationHandler : AuthenticationService
    {
        private readonly ILdapRepository _ldapRepository;
        public AuthenticationHandler(ILdapRepository ldapRepository,
            IAuthenticationSchemeProvider schemes, IAuthenticationHandlerProvider handlers,
            IClaimsTransformation transform) : base(schemes, handlers, transform)
        {
            _ldapRepository = ldapRepository;
        }
        public async override Task<AuthenticateResult> AuthenticateAsync(HttpContext context, string scheme)
        {
            var idk = await base.AuthenticateAsync(context, scheme);
            if (idk.Succeeded) {
                var claims = _ldapRepository.LoadClaimsFromActiveDirectory(idk.Principal.Claims.FirstOrDefault(x => x.Type == CustomClaimTypes.Name)?.Value);
                idk.Principal.AddIdentity(claims);
            }
            return idk;
        }
}

LdapRepository就是Active Directory类的DirectoryEntry和DirectorySearcher。

希望对您有帮助。