2016-11-02 58 views
2

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

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

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

我该怎么做?

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

Startup.Auth.cs需要什么?

+0

简短回答您提供的信息:是的。有可能的。 – Shyju

+0

@Shyju感谢您的回答,您的评论让我意识到我没有问过如何去做。我会更新这个问题。 – Lastwall

+0

我在MSDN博客https://blogs.msdn.microsoft.com/webdev/2013/07/03/understanding-owin-forms-authentication-in-mvc-5/上发现了以下文章,但似乎没有使用当前版本的ASP.NET MVC,因为代码中引用的对象上不存在方法。 – Lastwall

回答

4

我在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; 
    } 
} 

其次,您要创建将用于欧文中间件的声明。

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

谢谢,这就是我一直在寻找的。我正在查看GitHub仓库。 – Lastwall

+0

@那个项目是一个非常棒的资源,非常感谢你发布它,你为我们节省了很多天! – tomRedox

相关问题