2

我必须实现一个小型 REST 服务器来管理远程数据库,没什么特别的。安全性不是关键问题,因为该服务器必须在 Intranet 环境中运行;我们只想过滤用户并将他们重定向到适当的资源。

        HttpListener listener = new HttpListener();
        listener.Realm = "testserver1";
        listener.AuthenticationSchemes = AuthenticationSchemes.Basic;

        foreach (string s in prefixes)
        {
            listener.Prefixes.Add(s);
        }

        listener.Start();
        Console.WriteLine("Listening...");

        HttpListenerContext context = listener.GetContext();

        HttpListenerRequest request = context.Request;
        HttpListenerResponse response = context.Response;

        string responseString = "<HTML><BODY>" + DateTime.Now.ToString() + "</BODY></HTML>";
        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);

        response.ContentLength64 = buffer.Length;
        System.IO.Stream output = response.OutputStream;
        output.Write(buffer, 0, buffer.Length);
        output.Close();

        listener.Stop();

此代码(取自 Microsoft 站点)在服务器端完美运行,并且 - 当listener.GetContext()返回时 -我可以从 User 对象检查用户名和密码并确定如何处理请求。将初始listener.AuthenticationSchemes = AuthenticationSchemes.Basic更改为

listener.AuthenticationSchemes = AuthenticationSchemes.Digest

它像我预期的那样停止工作,并且像基本身份验证模式一样有效。listener.GetContext()调用永远不会返回。HttpListener 似乎阻止任何请求,并且从客户端继续提示我输入用户名和密码。我尝试了本地用户、本地管理员、域用户、域管理员,大约 500 个幻想名称:没有任何效果。GetContext() 不再返回。你能帮助我吗?

提前致谢。

L.

4

2 回答 2

1

分配给的值listener.Realm必须是用于身份验证的 Windows 域的名称。“testserver1”对我来说看起来不像一个域名。

于 2016-06-01T12:00:32.950 回答
0

您可以使用为我工作的 AuthenticationSchemeSelectorDelegate。例子:

_listener.AuthenticationSchemeSelectorDelegate = delegate(HttpListenerRequest request)
{
    string temp = request.Headers["Authorization"];
    if (!string.IsNullOrEmpty(temp))
        throw new Exception("Auth string: " + temp);
    return AuthenticationSchemes.Digest; // here where you return auth type for every request eg. can be Basic,Digest
};

http://msdn.microsoft.com/en-us/library/system.net.httplistener.authenticationschemeselectordelegate.aspx

于 2011-03-11T12:06:43.933 回答