3

我正在使用标准的简单会员模型通过我的应用程序中的表单登录。我想提供通过 AD 登录的可能性作为替代。

通过AD登录时,流程应该如下:

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

问题:我无法找回本地密码,所以为了在AD认证后本地登录,我需要能够在没有密码的情况下强制登录。

我考虑了以下策略:

  • 为 Websecurity 创建一个扩展方法以允许 Websecurity.Login(string username)
  • 以某种方式手动设置登录用户,而不涉及网络安全。

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

解决方案:

这最终成为正确的解决方案:

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

1 回答 1

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

希望这可以帮助。

于 2013-08-21T15:22:24.910 回答