如何使用Windows Active Directory身份验证和基于身份的声明?

问题描述 投票:29回答:5

问题

我们希望使用Windows Active Directory对用户进行应用程序身份验证。但是,我们不希望使用Active Directory组来管理控制器/视图的授权。

据我所知,没有一种简单的方法可以将AD和基于身份的声明结合起来。

目标

  • 使用本地Active Directory对用户进行身份验证
  • 使用Identity框架来管理声明

尝试(失败)

  • Windows.Owin.Security.ActiveDirectory - Doh。这适用于Azure AD。没有LDAP支持。他们可以将其称为AzureActiveDirectory吗?
  • Windows身份验证 - 使用NTLM或Keberos身份验证时可以。问题始于:i)令牌和索赔都由AD管理,我无法弄清楚如何使用身份声明。
  • LDAP - 但这些似乎迫使我手动进行表单身份验证以使用身份声明?当然必须有一个更简单的方法吗?

任何帮助都不仅仅是值得赞赏的。我已经坚持这个问题很长一段时间了,并且会对这个问题的外部投入表示赞赏。

authentication asp.net-identity claims-based-identity asp.net-core visual-studio-2015
5个回答
2
投票

鞋子上面的解决方案将我推向了一个对我有用的方向MVC6-Beta3 Identityframework7-Beta3 EntityFramework7-Beta3:

// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    //
    // Check for user existance in Identity Framework
    //
    ApplicationUser applicationUser = await _userManager.FindByNameAsync(model.eID);
    if (applicationUser == null)
    {
        ModelState.AddModelError("", "Invalid username");
        return View(model);
    }

    //
    // Authenticate user credentials against Active Directory
    //
    bool isAuthenticated = await Authentication.ValidateCredentialsAsync(
        _applicationSettings.Options.DomainController, 
        _applicationSettings.Options.DomainControllerSslPort, 
        model.eID, model.Password);
    if (isAuthenticated == false)
    {
        ModelState.AddModelError("", "Invalid username or password.");
        return View(model);
    }

    //
    // Signing the user step 1.
    //
    IdentityResult identityResult 
        = await _userManager.CreateAsync(
            applicationUser, 
            cancellationToken: Context.RequestAborted);

    if(identityResult != IdentityResult.Success)
    {
        foreach (IdentityError error in identityResult.Errors)
        {
            ModelState.AddModelError("", error.Description);
        }
        return View(model);
    }

    //
    // Signing the user step 2.
    //
    await _signInManager.SignInAsync(applicationUser,
        isPersistent: false,
        authenticationMethod:null,
        cancellationToken: Context.RequestAborted);

    return RedirectToLocal(returnUrl);
}

20
投票

只需使用用户名和密码命中AD,而不是针对您的数据库进行身份验证

// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        var user = await UserManager.FindByNameAsync(model.UserName);
        if (user != null && AuthenticateAD(model.UserName, model.Password))
        {
            await SignInAsync(user, model.RememberMe);
            return RedirectToLocal(returnUrl);
        }
        else
        {
            ModelState.AddModelError("", "Invalid username or password.");
        }
    }
    return View(model);
}

public bool AuthenticateAD(string username, string password)
{
    using(var context = new PrincipalContext(ContextType.Domain, "MYDOMAIN"))
    {
        return context.ValidateCredentials(username, password);
    }
}

4
投票

在ASPNET5(beta6)上,我们的想法是使用CookieAuthentication和Identity:你需要在你的Startup类中添加:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddAuthorization();
    services.AddIdentity<MyUser, MyRole>()
        .AddUserStore<MyUserStore<MyUser>>()
        .AddRoleStore<MyRoleStore<MyRole>>()
        .AddUserManager<MyUserManager>()
        .AddDefaultTokenProviders();
}

在configure部分中,添加:

private void ConfigureAuth(IApplicationBuilder app)
{
    // Use Microsoft.AspNet.Identity & Cookie authentication
    app.UseIdentity();
    app.UseCookieAuthentication(options =>
    {
        options.AutomaticAuthentication = true;
        options.LoginPath = new PathString("/App/Login");
    });
}

然后,您需要实现:

Microsoft.AspNet.Identity.IUserStore
Microsoft.AspNet.Identity.IRoleStore
Microsoft.AspNet.Identity.IUserClaimsPrincipalFactory

和扩展/覆盖:

Microsoft.AspNet.Identity.UserManager
Microsoft.AspNet.Identity.SignInManager

我实际上已经设置了一个示例项目来展示如何做到这一点。 GitHub Link

我测试了beta8和一些小的adapatons(如Context => HttpContext),它也有效。


3
投票

您可以使用ClaimTransformation,我今天下午使用下面的文章和代码让它工作。我正在访问具有窗口身份验证的应用程序,然后根据存储在SQL数据库中的权限添加声明。这篇文章应该对你有所帮助。

https://github.com/aspnet/Security/issues/863

综上所述 ...

services.AddScoped<IClaimsTransformer, ClaimsTransformer>();

app.UseClaimsTransformation(async (context) =>
{
IClaimsTransformer transformer = context.Context.RequestServices.GetRequiredService<IClaimsTransformer>();
return await transformer.TransformAsync(context);
});

public class ClaimsTransformer : IClaimsTransformer
    {
        private readonly DbContext _context;

        public ClaimsTransformer(DbContext dbContext)
        {
            _context = dbContext;
        }
        public async Task<ClaimsPrincipal> TransformAsync(ClaimsTransformationContext context)
        {

            System.Security.Principal.WindowsIdentity windowsIdentity = null;

            foreach (var i in context.Principal.Identities)
            {
                //windows token
                if (i.GetType() == typeof(System.Security.Principal.WindowsIdentity))
                {
                    windowsIdentity = (System.Security.Principal.WindowsIdentity)i;
                }
            }

            if (windowsIdentity != null)
            {
                //find user in database by username
                var username = windowsIdentity.Name.Remove(0, 6);
                var appUser = _context.User.FirstOrDefault(m => m.Username == username);

                if (appUser != null)
                {

                    ((ClaimsIdentity)context.Principal.Identity).AddClaim(new Claim("Id", Convert.ToString(appUser.Id)));

                    /*//add all claims from security profile
                    foreach (var p in appUser.Id)
                    {
                        ((ClaimsIdentity)context.Principal.Identity).AddClaim(new Claim(p.Permission, "true"));
                    }*/

                }

            }
            return await System.Threading.Tasks.Task.FromResult(context.Principal);
        }
    }

1
投票

你知道如何实现自定义System.Web.Security.MembershipProvider吗?你应该能够使用它(覆盖ValidateUser)和System.DirectoryServices.AccountManagement.PrincipalContext.ValidateCredentials()来对活动目录进行身份验证。

尝试: var pc = new PrincipalContext(ContextType.Domain, "example.com", "DC=example,DC=com"); pc.ValidateCredentials(username, password);

© www.soinside.com 2019 - 2024. All rights reserved.