c# - 使用 Active Directory 使用本地用户登录

标签 c# entity-framework security asp.net-mvc-4

我在我的应用程序中使用标准的简单成员(member)模型通过表单登录。作为替代方案,我想提供通过 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");
    }

最佳答案

这就是 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;
}

希望这对您有所帮助。

关于c# - 使用 Active Directory 使用本地用户登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18360918/

相关文章:

c# - 如何在后台启动进程?

C# 存储库实现,需要有关通用修复的建议

c# - 如何在基于MVC4/EF 6+的应用中实现事务

sql-server - 这个黑客想做什么?

security - Codeigniter 定义基本路径或退出

用于密码存储的 asp.net keystore ?

c# - 发布base64转换后的图像数据

c# - UpdatePanel Gridview 不更新

c# - MVC4 EF代码在生产中首先数据库初始化不完整

entity-framework - 在具有现有父项的 EF 中添加新记录