简体   繁体   中英

c# Impersonate user after forms authentification

Untill today, I used windowd authentification for my society intranet (built in asp mvc 3.0). However, because an urgent need to log of users, I had to pass to forms authentification.

All it's good now, except one function that I used for explore a directory in the server. Depending of the of user rights, the user could read some directories and files. This is my function:

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

Of course, with forms authentification, i can't get windows identity from HttpContext user. How I can read directories and files now?

PS: I tried to use the advapi32.dll to get windows identity of the user. However, after the logon, it's impossible to logout without closing the browser (ssi). That is why I search another solution. Is it possible to get windows identity token whithout logon?

Thanks

Probably not safe, nor recommended. But you could persist the username and password in a Session var or something. Then use Impersonation when needed via this class .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM