WebSocket for real-time communication in C# and Typescript — Part 2 (Authentication)

Muhammad Rizwan
2 min readJan 14, 2023

--

Photo by Markus Spiske on Unsplash

This one extraction to previous work, first look a part 1.

There are several ways to add authentication to a WebSocket server, but one common approach is to use JSON Web Tokens (JWT). With this approach, the client would need to obtain a JWT from an authentication server, and then send the JWT in the WebSocket request to the server. The server can then verify the JWT and authenticate the client.

Here’s an example of how you could modify the previous C# WebSocket server code to include JWT-based authentication:

In this example, the server is checking for the presence of an “Authorization” header in the WebSocket request. If the header is present and starts with “Bearer “, the server will attempt to parse the JWT from the header value and validate it. If the JWT is valid, the server will proceed with accepting the WebSocket connection and starting a new task to handle the socket. If the JWT is not present or is invalid, the server will respond with a 401 Unauthorized or 403 Forbidden status code and close the connection.

As for the client-side, the client should obtain a JWT from an authentication server and then include the JWT in the “Authorization” header of the WebSocket request.

In this example, the client is using the jsonwebtoken library to generate a JWT, which is then included in the headers of the WebSocket request.

Please keep in mind that, JWT validation/generation should be done securely, and JWT Secret should be kept private, also you can use different libraries and approaches that fits your use case.

In next part we add Data Serialization, Security and scalability.

--

--

Muhammad Rizwan

Hello with islamic greetings As-Salam-u-Alaikum, I'm Muhammad Rizwan a freelance Games & Software developer based in Lahore.