代码之家  ›  专栏  ›  技术社区  ›  FWH

httplistener:如何获取HTTP用户和密码?

  •  9
  • FWH  · 技术社区  · 15 年前

    我和httplistener在这里遇到了一个问题。

    当表单的请求

    http://user:password@example.com/
    

    是的,如何获取用户和密码? httpwebrequest有一个credentials属性,但httplistenerrequest没有该属性,并且在它的任何属性中都找不到用户名。

    谢谢你的帮助。

    3 回复  |  直到 10 年前
        1
  •  21
  •   csharpfolk    11 年前

    您要做的是通过HTTP基本身份验证传递凭据,我不确定httplistener中是否支持用户名:密码语法,但如果支持,则需要指定您首先接受基本身份验证。

    HttpListener listener = new HttpListener();
    listener.Prefixes.Add(uriPrefix);
    listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
    listener.Start();
    

    收到请求后,可以使用以下命令提取用户名和密码:

    HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)context.User.Identity;
    Console.WriteLine(identity.Name);
    Console.WriteLine(identity.Password);
    

    Here's a full explanation 可以与httpListener一起使用的所有受支持的身份验证方法。

        2
  •  4
  •   anonymous coward    15 年前

    得到 Authorization 标题。它的格式如下

    Authorization: <Type> <Base64-encoded-Username/Password-Pair>
    

    例子:

    Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
    

    用户名和密码是用冒号分隔的(在本例中, Aladdin:open sesame ,然后B64编码。

        3
  •  2
  •   Darin Dimitrov    15 年前

    您需要首先启用基本身份验证:

    listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
    

    然后,在processRequest方法中,您可以获取用户名和密码:

    if (context.User.Identity.IsAuthenticated)
    {
        var identity = (HttpListenerBasicIdentity)context.User.Identity;
        Console.WriteLine(identity.Name);
        Console.WriteLine(identity.Password);
    }