The sgcWebSockets library supports multiple authentication methods to secure WebSocket communication in Delphi and C++Builder applications. Since the WebSocket protocol itself doesn't define an authentication mechanism, sgcWebSockets implements its own set of techniques suitable for both server and client sides.

Supported Authentication Types

The library supports the following main authentication methods:

  1. Session Authentication
  2. URL Authentication
  3. Basic Authentication
  4. OAuth2
  5. JWT (JSON Web Tokens)
  6. WebAuthn (Web Authentication)

1. Session Authentication

 The client performs an HTTP GET request to receive a session token:

http://host:port/sgc/req/auth/session/:user/:password

The server responds with a token, which is then used in the WebSocket URL:

ws://host:port/sgc/auth/session/:token

Properties

Authentication.Enabled := True;

Advantages

  • Token-based access makes it secure and simple.
  • Suitable for applications with a login system.

Example

Client.URL := 'ws://localhost:443/sgc/auth/session/your-token';

2. URL Authentication

Credentials are included directly in the WebSocket URL: 

ws://host:port/sgc/auth/url/username/password

Advantages

  • Very simple to implement.
  • Compatible with browser-based WebSocket clients.

Disadvantages

  • Credentials are exposed in the URL.
  • Should only be used with SSL/TLS.

3. Basic Authentication

Uses the standard HTTP Authorization header:

Authorization: Basic base64(user:password)

Properties

Authentication.AuthUsers := 'user=password';

Use the OnAuthentication event for custom validation.

Advantages
  • Simple and familiar.
  • Server manages a list of valid users.

Example

procedure WSServerAuthentication(Connection: TsgcWSConnection; aUser, aPassword: string; var Authenticated: Boolean);
begin
  if (aUser = 'John') and (aPassword = '1234') then
    Authenticated := True;

end;

4. OAuth2 Authentication

OAuth2 is supported through components such as TsgcHTTP_OAuth2_Server and TsgcHTTP_OAuth2_Client.
It works with providers like Google, Microsoft, Azure AD, and custom identity systems.

Key Events
  • OnOAuth2Authentication
  • OnOAuth2AfterAccessToken
Advantages
  • Modern and secure.
  • Well-suited for web applications and cloud environments.


5. JWT Authentication

Authentication is performed using JSON Web Tokens (JWT). Tokens can be passed either in the query string or in HTTP headers.

Properties

Authentication.TokenParam := srctQuery
Authentication.TokenParam := srctHeader

Components: TsgcHTTP_JWT_Client, TsgcHTTP_JWT_Server

Advantages
  • Stateless and scalable.
  • Widely adopted, integrates easily with external services.

6. WebAuthn Authentication

WebAuthn is based on the FIDO2 standard and uses public key cryptography. It enables passwordless authentication.

Components

TsgcWSAPIServer_WebAuthn

Advantages
  • Very strong security.
  • Resistant to phishing and credential theft.

7. Comparison Table