Http Authentication using WebSocket4Net

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

Answers


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.


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

Need Your Help

WCF client-side error-handling

c# wcf wcf-client

I'm consuming a clunky WCF server that occasionally throws various exceptions, and additionally returns some of its errors as string. I have no access to the server code at all.

Create Dynamic fileupload api in php

php api file-upload

I am working on file upload api in php. For Now I just create this simple php which will upload the file from an html page to server. But in this code the fileupload control's name is fixed so I pass