質問

Is there a way to Http Authentication with WebSocket4Net? I would like to pass credentials to my client. This is what my code looks like:

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;
}
役に立ちましたか?

解決 2

Thanks J.C for the Link. I used it to create a little helper class.

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

他のヒント

I'm not sure that I understand your question clearly, but I still try to help.

Do you mean you're developing a web service, and need "Basic HTTP Authentication"?

If you're doing the server side, and require an authentication, you can response HTTP 401 first.

Most of browser will notify user when it received HTTP 401.

If you're doing the client side, and you want to send authentication automatically,

you can refer to the issue of WebSocket4Net.

Please notice that Basic HTTP Authentication is PLAIN TEXT.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top