2013-08-21 63 views
3

我正在使用标准的简单成员资格模型登录通过我的应用程序中的窗体。我想提供通过AD登录作为替代的可能性。使用Active Directory登录使用本地用户

当经由AD登录,这个过程应该是如下:

  1. 检查AD对用户进行认证,但不使用用于主要的信息。
  2. 检查是否有任何本地用户存在提供的Active Directory用户名(我在我的UserProfile模型上有一个名为ActiveDirectoryID的属性)。
  3. 如果存在,请使用本UserProfile的本地用户名执行本地登录。

问题:我无法检索本地密码,所以为了在AD身份验证后本地登录,我需要能够强制登录而不使用密码。

我已经考虑以下策略:

  • 创建一个扩展方法Websecurity允​​许Websecurity.Login(用户名字符串)
  • 莫名其妙定置登录的用户手动,没有牵连Websecurity。

这是可行的吗?框架是否有可能在没有明文密码的情况下创建必要的身份验证cookie?我该怎么做?

SOLUTION:

就这样结束是正确的解决方案:

public ActionResult ActiveDirectoryLogin(LoginModel model, string returnUrl) 
    { 
     if (ModelState.IsValid) 
     { 
      try 
      { 
       DirectoryEntry entry = new DirectoryEntry("LDAP://DC=MyIntranet,DC=MyCompany,DC=com", model.UserName, model.Password); 
       object NativeObject = entry.NativeObject; 

       var internalUser = db.UserProfiles.Where(x => x.ActiveDirectoryID == model.UserName).SingleOrDefault(); 

       if (internalUser != null) 
       { 
        FormsAuthentication.SetAuthCookie(internalUser.UserName, model.RememberMe); 
        return RedirectToLocal(returnUrl); 
       } 
      } 
      catch (DirectoryServicesCOMException) 
      { 
       // No user existed with the given credentials 
      } 
      catch (InvalidOperationException) 
      { 
       // Multiple users existed with the same ActiveDirectoryID in the database. This should never happen! 
      } 
     } 

     return RedirectToAction("Login"); 
    } 

回答

2

这是所有的Websecurity.Login方法做:

public static bool Login(string userName, string password, bool persistCookie = false) 
{ 
    WebSecurity.VerifyProvider(); 
    bool flag = Membership.ValidateUser(userName, password); 
    if (flag) 
    { 
     FormsAuthentication.SetAuthCookie(userName, persistCookie); 
    } 
    return flag; 
} 

你可以写你自己的方法对AD进行身份验证,然后查找用户名,并将身份验证cookie设置为如下形式:

public static bool MyLogin(string userName, string password, bool persistCookie = false) 
{ 
    bool flag = CheckADUser(userName, password); 

    if (flag) 
    { 
     string mappedUsername = GetMappedUser(userName); 
     if(mappedUsername != "") 
     { 
      FormsAuthentication.SetAuthCookie(userName, persistCookie); 
     } 
     else 
     { 
      flag = false; 
     } 
    } 
    return flag; 
} 

希望这会有所帮助。

+0

辉煌。你肯定会把我放在正确的轨道上,尽管WebSecurity由于是静态的而变成不可扩展的。我在上面的答案中提供了最终解决方案。 –

相关问题