[windows-7] HttpListener 액세스가 거부되었습니다.

C #으로 HTTP 서버를 작성 중입니다.

함수를 실행하려고 HttpListener.Start()하면 HttpListenerException말이 나타납니다.

“접근 불가”.

Windows 7에서 관리자 모드로 앱을 실행하면 정상적으로 작동합니다.

관리자 모드없이 실행할 수 있습니까? 그렇다면 어떻게? 그렇지 않은 경우 실행을 시작한 후 앱을 관리자 모드로 변경하려면 어떻게해야합니까?

using System;
using System.Net;

namespace ConsoleApplication1
{
    class Program
    {
        private HttpListener httpListener = null;

        static void Main(string[] args)
        {
            Program p = new Program();
            p.Server();
        }

        public void Server()
        {
            this.httpListener = new HttpListener();

            if (httpListener.IsListening)
                throw new InvalidOperationException("Server is currently running.");

            httpListener.Prefixes.Clear();
            httpListener.Prefixes.Add("http://*:4444/");

            try
            {
                httpListener.Start(); //Throws Exception
            }
            catch (HttpListenerException ex)
            {
                if (ex.Message.Contains("Access is denied"))
                {
                    return;
                }
                else
                {
                    throw;
                }
            }
        }
    }
}



답변

예, 비 관리자 모드에서 HttpListener를 실행할 수 있습니다. 특정 URL에 권한을 부여하기 만하면됩니다. 예 :

netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user

설명서는 여기에 있습니다 .


답변

관리자 모드없이 실행할 수 있습니까? 그렇다면 어떻게? 그렇지 않은 경우 실행을 시작한 후 앱을 관리자 모드로 변경하려면 어떻게해야합니까?

높은 권한으로 시작해야합니다. runas동사를 사용하여 다시 시작하면 관리자 모드로 전환하라는 메시지가 표시됩니다.

static void RestartAsAdmin()
{
    var startInfo = new ProcessStartInfo("yourApp.exe") { Verb = "runas" };
    Process.Start(startInfo);
    Environment.Exit(0);
}

편집 : 실제로, 그것은 사실이 아닙니다. HttpListener는 상승 된 권한없이 실행될 수 있지만 청취하려는 URL에 대한 권한을 부여해야합니다. 자세한 내용은 Darrel Miller의 답변 을 참조하십시오.


답변

http://localhost:80/접두사로 사용 하면 관리 권한이 없어도 http 요청을들을 수 있습니다.


답변

구문이 잘못되었습니다. 따옴표를 포함시켜야합니다.

netsh http add urlacl url="http://+:4200/" user=everyone

그렇지 않으면 “매개 변수가 잘못되었습니다”라는 메시지가 나타납니다.


답변

“user = Everyone”플래그를 사용하려면 시스템 언어에 맞게 조정해야합니다. 영어로 언급 된 바와 같이 :

netsh http add urlacl url=http://+:80/ user=Everyone

독일어로는 다음과 같습니다.

netsh http add urlacl url=http://+:80/ user=Jeder


답변

권한 상승 또는 netsh가 필요없는 대안으로 예를 들어 TcpListener를 사용할 수도 있습니다.

다음은이 샘플의 수정 된 발췌 부분입니다.
https://github.com/googlesamples/oauth-apps-for-windows/tree/master/OAuthDesktopApp

// Generates state and PKCE values.
string state = randomDataBase64url(32);
string code_verifier = randomDataBase64url(32);
string code_challenge = base64urlencodeNoPadding(sha256(code_verifier));
const string code_challenge_method = "S256";

// Creates a redirect URI using an available port on the loopback address.
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
string redirectURI = string.Format("http://{0}:{1}/", IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port);
output("redirect URI: " + redirectURI);

// Creates the OAuth 2.0 authorization request.
string authorizationRequest = string.Format("{0}?response_type=code&scope=openid%20profile&redirect_uri={1}&client_id={2}&state={3}&code_challenge={4}&code_challenge_method={5}",
    authorizationEndpoint,
    System.Uri.EscapeDataString(redirectURI),
    clientID,
    state,
    code_challenge,
    code_challenge_method);

// Opens request in the browser.
System.Diagnostics.Process.Start(authorizationRequest);

// Waits for the OAuth authorization response.
var client = await listener.AcceptTcpClientAsync();

// Read response.
var response = ReadString(client);

// Brings this app back to the foreground.
this.Activate();

// Sends an HTTP response to the browser.
WriteStringAsync(client, "<html><head><meta http-equiv='refresh' content='10;url=https://google.com'></head><body>Please close this window and return to the app.</body></html>").ContinueWith(t =>
{
    client.Dispose();
    listener.Stop();

    Console.WriteLine("HTTP server stopped.");
});

// TODO: Check the response here to get the authorization code and verify the code challenge

읽기 및 쓰기 방법은 다음과 같습니다.

private string ReadString(TcpClient client)
{
    var readBuffer = new byte[client.ReceiveBufferSize];
    string fullServerReply = null;

    using (var inStream = new MemoryStream())
    {
        var stream = client.GetStream();

        while (stream.DataAvailable)
        {
            var numberOfBytesRead = stream.Read(readBuffer, 0, readBuffer.Length);
            if (numberOfBytesRead <= 0)
                break;

            inStream.Write(readBuffer, 0, numberOfBytesRead);
        }

        fullServerReply = Encoding.UTF8.GetString(inStream.ToArray());
    }

    return fullServerReply;
}

private Task WriteStringAsync(TcpClient client, string str)
{
    return Task.Run(() =>
    {
        using (var writer = new StreamWriter(client.GetStream(), new UTF8Encoding(false)))
        {
            writer.Write("HTTP/1.0 200 OK");
            writer.Write(Environment.NewLine);
            writer.Write("Content-Type: text/html; charset=UTF-8");
            writer.Write(Environment.NewLine);
            writer.Write("Content-Length: " + str.Length);
            writer.Write(Environment.NewLine);
            writer.Write(Environment.NewLine);
            writer.Write(str);
        }
    });
}


답변

응용 프로그램 매니페스트를 프로젝트에 추가하면 응용 프로그램을 관리자로 시작할 수 있습니다.

프로젝트에 새 항목을 추가하고 “응용 프로그램 매니페스트 파일”을 선택하십시오. <requestedExecutionLevel>요소를 다음과 같이 변경하십시오 .

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />