2009-07-18 156 views

回答

21

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

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

的可与HttpListener使用所有支持authenitcation方法Here's a full explanation

+0

对不起,我说:“我不是,如果用户名: HttpListener支持密码语法“,但当然是客户端将它转换为”WWW-Authenticate:basic“头,因此只有客户端支持时才重要。我相信最近对IE的支持已经下降了。 – 2009-07-18 11:44:50

4

获取Authorization标题。它的格式如下

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

实施例:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== 

的用户名和口令是冒号分隔(在这个例子中,Aladdin:open sesame),然后B64编码。

2

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

listener.AuthenticationSchemes = AuthenticationSchemes.Basic; 

然后在您的ProcessRequest方法,你可以得到的用户名和密码:

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