2011-12-08 3 views
2

HTTP基本認証を要求するサーバーがWWW-Authenticateヘッダーで送信したRealmプロパティを読み取るにはどうすればよいですか?HTTP認証でRealmプロパティを読み取る

+1

タイトルの繰り返しは本当に役立ちません。もう少し詳しく説明してください。 – Ryan

+1

十分にクリアです。私は私が望む助けを得る。ありがとう – T4mer

答えて

8

ダウン有権者がこの質問を持っている問題は本当に何であるか本当にわかりません。

ここでは、基本認証領域を含むWWW-Authenticateヘッダーを取得するための概略的なコードを示します。ヘッダーから実際のレルム値を抽出することは練習問題として残されていますが、(たとえば正規表現を使用して)非常に簡単なはずです。

public static string GetRealm(string url) 
{ 
    var request = (HttpWebRequest)WebRequest.Create(url); 
    try 
    { 
     using (request.GetResponse()) 
     { 
      return null; 
     } 
    } 
    catch (WebException e) 
    { 
     if (e.Response == null) return null; 
     var auth = e.Response.Headers[HttpResponseHeader.WwwAuthenticate]; 
     if (auth == null) return null; 
     // Example auth value: 
     // Basic realm="Some realm" 
     return ...Extract the value of "realm" here (with a regex perhaps)... 
    } 
} 
+1

本当に助けになります。 ありがとうございます – T4mer

+0

はい。これはまさに私が必要としていたものです。私はこれを使用して、Kerberos WebサイトでホストされているWebサービスに接続しようとしているかどうかを判断します。 – DaleyKD

2

基本認証を使用してWebリクエストを作成することを前提としています。

それは正しい仮定だ場合は、次のコードでは、何が必要です:

// Create a request to a URL 
WebRequest myReq = WebRequest.Create(url); 
string usernamePassword = "username:password"; 
//Use the CredentialCache so we can attach the authentication to the request 
CredentialCache mycache = new CredentialCache(); 
mycache.Add(new Uri(url), "Basic", new NetworkCredential("username", "password")); 
myReq.Credentials = mycache; 
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword))); 
//Send and receive the response 
WebResponse wr = myReq.GetResponse(); 
Stream receiveStream = wr.GetResponseStream(); 
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8); 
string content = reader.ReadToEnd();