繁体   English   中英

使用Owin中间件进行Active Directory身份验证的ASP.Net MVC

[英]ASP.Net MVC with Active Directory Authentication using Owin Middleware

我需要创建一个ASP.NET MVC 5应用程序,它将使用表单(如使用个人用户帐户时)进行登录,但不使用数据库中的用户信息,而是使用Windows / AD帐户和凭据。

换句话说,比如使用Windows身份验证但使用html表单而不是弹出Windows身份验证通常会显示。 这可能吗?

理想情况下,身份验证将降级到IIS并使用相同的协议,并根据角色允许或拒绝用户。

我怎样才能做到这一点?

我需要在web.config中配置什么?

我需要在Startup.Auth.cs中拥有什么?

我在GitHub上创建了一个名为AspNetMvcActiveDirectoryOwin的示例项目。 你可以分叉吧。

您需要遵循以下几个步骤 -

首先,您要使用Active Directory进行身份验证。

public class ActiveDirectoryService : IActiveDirectoryService
{
    public bool ValidateCredentials(string domain, string userName, string password)
    {
        using (var context = new PrincipalContext(ContextType.Domain, domain))
        {
            return context.ValidateCredentials(userName, password);
        }
    }

    public User GetUser(string domain, string userName)
    {
        User result = null;
        using (var context = new PrincipalContext(ContextType.Domain, domain))
        {
            var user = UserPrincipal.FindByIdentity(context, userName);
            if (user != null)
            {
                result = new User
                {
                    UserName = userName,
                    FirstName = user.GivenName,
                    LastName = user.Surname
                };
            }
        }
        return result;
    }
}

其次,您要创建将在Owin Middleware中使用的声明。

public class OwinAuthenticationService : IAuthenticationService
{
    private readonly HttpContextBase _context;
    private const string AuthenticationType = "ApplicationCookie";

    public OwinAuthenticationService(HttpContextBase context)
    {
        _context = context;
    }

    public void SignIn(User user)
    {
        IList<Claim> claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, user.UserName),
            new Claim(ClaimTypes.GivenName, user.FirstName),
            new Claim(ClaimTypes.Surname, user.LastName),
        };

        ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);

        IOwinContext context = _context.Request.GetOwinContext();
        IAuthenticationManager authenticationManager = context.Authentication;

        authenticationManager.SignIn(identity);
    }

    public void SignOut()
    {
        IOwinContext context = _context.Request.GetOwinContext();
        IAuthenticationManager authenticationManager = context.Authentication;

        authenticationManager.SignOut(AuthenticationType);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM