c#在表单身份验证后模拟用户

时间:2014-05-15 15:40:20

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

直到今天,我在我的社会内联网(内置于asp mvc 3.0)中使用了窗口认证。但是,由于迫切需要记录用户,我不得不传递给表单验证。

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

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身份令牌?

谢谢

1 个答案:

答案 0 :(得分:1)

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

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