简体   繁体   中英

How to create a websocket to a URL using "Authorization", "Bearer", token in c#

I need to create a websocket to a particular url(cannot reveal) in c#. Is there something similar to the WebSocket API in Java, or libwebsockets in C for C#?

I have already tried using WebSocketSharp and ChilKat by following some of the SO answers. Also tried using the Microsofts WebSocket Namespace. But was always getting the "Not Authorized" error 401. I also tried doing an Http get and tried to add headers to upgrade the socket to Websocket by following the tutorial to create WebSocket servers in the MDN docs, but was only getting a redirected webpage in return. This is the code I used for the HTTP upgrade request. I am a beginner to c#.

ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                                                    | SecurityProtocolType.Tls11
                                                    | SecurityProtocolType.Tls12
                                                    | SecurityProtocolType.Ssl3;
            ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) =>
            {
                return true;
            };
            var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
            http.AllowAutoRedirect = false;
            http.UseDefaultCredentials = true;
            http.PreAuthenticate = true;
            http.Credentials = CredentialCache.DefaultCredentials;
            http.Proxy.Credentials = CredentialCache.DefaultCredentials;
            http.Accept = "application/json";
            http.ContentType = "application/json";
            http.Method = "GET";
            http.Connection = "Open";
            http.Headers.Add("Authorization", "Bearer " + Token);
            //http.Headers.Add("Connection", "Upgrade");
            http.Headers.Add("Upgrade", "websocket");
            http.KeepAlive = true;

What I want to achieve is something like,

Websocket socket = new Websocket();
socket.addHeader(Authorization, Bearer, Token);
socket.connect(); 

Thanks in Advance for any inputs.

I am using ClientWebSocket to connect to the Zendesk chat streaming API using an OAuth token like this:

var webSocket = new ClientWebSocket();
webSocket.Options.SetRequestHeader("Authorization", $"Bearer {_oauthToken}");
var cts = new CancellationTokenSource();
await webSocket.ConnectAsync(new Uri(url), cts.Token);

It works for me!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM