2014-02-05 55 views
0

有沒有辦法通過WebSocket4Net進行Http身份驗證?我想將憑據傳遞給我的客戶。這是我的代碼看起來像:使用WebSocket4Net的Http身份驗證

public bool Connect(string uri, ICredentials credentials = null) 
{ 
    if (this.ws == null) 
    { 
    try 
    { 
     ////this.ws = new WebSocket(uri, string.Empty, WebSocketVersion.None, null,); 
     this.ws = new WebSocket(uri); 
     this.ws.Opened += this.OnWebSocketOpen; 
     this.ws.Closed += this.OnWebSocketClose; 
     this.ws.Error += this.OnWebSocketFail; 
     this.ws.MessageReceived += this.OnWebSocketMessage; 

     try 
     { 
     this.ws.Open(); 
     return true; 
     } 
     catch (Exception ex) 
     { 
     Log.Error("Open web socket failed", ex); 
     this.ws = null; 
     } 
    } 
    catch (Exception exception) 
    { 
     throw new CanNotConnectToDeviceException(new Uri(uri, UriKind.Relative), exception); 
    } 
    } 

    return false; 
} 
+0

你解決了這個問題嗎?或者我應該關注它嗎? –

回答

0

感謝J.C的鏈接。我用它來創建一個小幫手類。

public class HttpHelper : IHttpHelper 
{ 
     public KeyValuePair<string, string> 
      CreateAuthorizationHeader(ICredentials credentials) 
     { 
      NetworkCredential networkCredential = 
       credentials.GetCredential(null, null); 

      string userName = networkCredential.UserName; 
      string userPassword = networkCredential.Password; 

      string authInfo = userName + ":" + userPassword; 
      authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); 

      return new KeyValuePair<string, string>("Authorization", "Basic " + authInfo); 
    } 
} 
1

我不知道我明白你的問題,但我仍然試圖幫助。

你的意思是你正在開發一個Web服務,並且需要「基本的HTTP認證」?

如果您在服務器端進行身份驗證,您可以首先響應HTTP 401。

當它收到HTTP 401

如果你正在做的客戶端瀏覽器的大多數將通知用戶,並要自動發送驗證,

你可以參考the issue of WebSocket4Net

請注意,基本HTTP身份驗證是PLAIN TEXT。

+0

我正在開發一個通過websocket連接到設備的應用程序。 – Kingpin

+0

因此,您的設備正在運行Web服務,並等待用戶通過您的應用程序連接到它,對吧? –

+0

是的,這是正確的 – Kingpin

相關問題