HttpListenerException "access denied" for non-admins

Mossi picture Mossi · Feb 19, 2013 · Viewed 34.2k times · Source

I have written a C# application that uses HttpListener to listen for HTTP requests -obviously! The namespace prefix I use is also registered using netsh for the current user (as suggested by everyone on SO).

The problem is despite using netsh my application still throws an "access is denied" exception for non-admin users. The OS is Windows 7.

Update: It appears as though my application is not executing the netsh command when I run it with a non-admin user. Is there any problems with my code? There are no exceptions thrown.

    AddAddress("http://localhost:8400/", Environment.UserDomainName, Environment.UserName);

    HttpListener _listener = new HttpListener();
    _listener.Prefixes.Add("http://localhost:8400/");
    _listener.Start();

    ...

    /** method stolen from an SO thread. sorry can't remember the author **/
    static void AddAddress(string address, string domain, string user)
    {
        string args = string.Format(@"http add urlacl url={0}", address) + " user=\"" + domain + "\\" + user + "\"";

        ProcessStartInfo psi = new ProcessStartInfo("netsh", args);
        psi.Verb = "runas";
        psi.CreateNoWindow = true;
        psi.WindowStyle = ProcessWindowStyle.Hidden;
        psi.UseShellExecute = true;

        Process.Start(psi).WaitForExit();
    }

Answer

Jim Mischel picture Jim Mischel · Feb 20, 2013

The line that I use when I'm doing an HttpListener is:

netsh http add urlacl url=http://+:8008/ user=Everyone listen=yes

The user can be an individual user or a user group. So if you want only Administrators to have access, for example:

netsh http add urlacl url=http://+:8008/ user=Administrators listen=yes

You can get help on the command:

netsh http add urlacl help

Note that the url= is optional. Also, older versions of the command require true or false for the listen parameter. Current versions use yes or no.