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

标签 c# .net asp.net-mvc

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

换句话说,就像使用 Windows 身份验证一样,但使用 html 表单而不是通常显示的弹出式 Windows 身份验证。 这可能吗?

理想情况下,身份验证应委托(delegate)给 IIS 并使用相同的协议(protocol),并根据角色允许或拒绝用户。

我该怎么做?

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

我需要在 Startup.Auth.cs 中包含什么?

最佳答案

我在 GitHub 上创建了一个名为 AspNetMvcActiveDirectoryOwin 的示例项目.你可以 fork 它。

您需要执行几个步骤 -

首先,您要使用 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 中间件中使用的声明。

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);
    }
}

关于c# - 使用 Owin 中间件进行 Active Directory 身份验证的 ASP.Net MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40383287/

相关文章:

c# - 如何使用数据注释属性类来使表单中的空字符串失效?

c# - 如何动态显示上月名称

.net - 如何读取网页浏览器控件的html内容?

c# - 处理返回的 ASP.NET MVC FileResult

asp.net-mvc - 当我发布到 Azure 时,ASP MVC4 和 Azure - 捆绑和缩小不再为我工作

c# - 在 Xunit 集成测试中检索 ASP.NET Core 3.1 数据库上下文

javascript - 使用 ASP.NET WCF 服务 JSON 发布数据

c# - 需要建议 - 如何编写绘图程序

c# - 是否有可能将委托(delegate)的执行从一个线程移动到另一个中间执行?

asp.net-mvc - ASP.NET MVC 文件夹约定