2009-07-18 42 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); 
}