【问题标题】:c# Impersonate user after forms authentificationc#表单认证后模拟用户
【发布时间】:2014-05-15 15:40:20
【问题描述】:

直到今天,我对我的社会 Intranet 使用窗口身份验证(内置于 asp mvc 3.0)。但是因为急需用户的登录,只好通过forms认证。

现在一切都很好,除了我用来探索服务器中目录的一个功能。根据用户权限,用户可以读取一些目录和文件。这是我的功能:

public static MvcHtmlString Explore()
    {
        WindowsIdentity id = (WindowsIdentity)HttpContext.Current.User.Identity;

        MvcHtmlString s = null;
        using (System.Security.Principal.WindowsImpersonationContext context = System.Security.Principal.WindowsIdentity.Impersonate(id.Token))
        {
            try
            {
                s = new MvcHtmlString(Explore(documentsRootFolder).ToString());
            }
            catch (Exception e)
            {
                HttpContext.Current.Response.Write(e.Message+"<br/>");
                HttpContext.Current.Response.Write(e.StackTrace);
            }
        }
        return s;
    }

    private static StringBuilder Explore(string path)
    {

        StringBuilder writer = new StringBuilder();
        writer.Append("<ul>");
        try
        {
            foreach (var a in System.IO.Directory.GetDirectories(path))
            {
                writer.AppendFormat("<li>{0}</li>", a.Replace((path.EndsWith(@"\") ? path : path+@"\"), string.Empty));
                writer.Append(Explore(a));

            }

            foreach (var a in System.IO.Directory.GetFiles(path))
            {
                string url = a.Replace(documentsRootFolder, string.Empty).Replace(@"\", "/");
                string friendlyName = a.Replace((path.EndsWith(@"\") ? path : path + @"\"), string.Empty);
                writer.AppendFormat("<li><a href=\"Open?path={0}\">{1}</a></li>", url, friendlyName);
            }
        }
        catch { }
        writer.Append("</ul>");
        return writer;
    }

当然,通过表单身份验证,我无法从 HttpContext 用户获取 Windows 身份。我现在如何读取目录和文件?

P.S:我尝试使用 advapi32.dll 来获取用户的 windows 身份。但是,登录后,如果不关闭浏览器(ssi)就无法注销。这就是我寻找另一个解决方案的原因。是否可以在不登录的情况下获取 Windows 身份令牌?

谢谢

【问题讨论】:

  • 如果您在 Intranet 应用程序中出于安全考虑需要自动注销用户,您是否考虑过要求 IT 管理员强制 Windows 会话自动锁定,因为它可能会达到相同的目的.
  • 不,我也想让用户在他们想要的时候登录(例如,用另一个用户帐户登录...)

标签: c# asp.net-mvc-3 impersonation form-authentication


【解决方案1】:

可能不安全,也不推荐。但是您可以将用户名和密码保存在 Session var 或其他内容中。然后在需要时通过this class 使用模拟。

using(new Impersonation("username","domain","password"))
{
  s = new MvcHtmlString(Explore(documentsRootFolder).ToString());
}

【讨论】:

  • 将用户的凭据保存在 Session 变量中,这可能是有问题的。
  • 如果我在会话中存储 Impersantion 对象并在用户注销时将其处理掉,这样是否更安全?
  • 不,不要那样做。仅在实际需要模拟时使用 Impersonation 类。
猜你喜欢
  • 2013-10-03
  • 2011-04-06
  • 1970-01-01
  • 2016-08-17
  • 1970-01-01
  • 1970-01-01
  • 2016-05-14
  • 2020-05-23
  • 1970-01-01
相关资源
最近更新 更多