Pusher のカスタム認証

· 機能

sgcWebSockets 2022.1 より、sgcWebSockets Pusher クライアントで独自のカスタム認証を実装できるようになりました。

Pusher では、認証トークンを提供した接続のみがプライベートまたはプレゼンスチャネルにサブスクライブできます。これによりアクセスを制限できます。

OnPusherAuthentication イベントを使用して独自の認証フローを構築できます。このイベントは、Pusher が提供するシークレットキーでサブスクリプションメッセージが署名される前に呼び出されます。このイベントには 2 つのパラメータがあり、SocketId やチャンネル名などのフィールドを持つ認証リクエストを独自の認証サーバーで認証するかどうかの判断に使用できます。以下は Pusher の認証フローを示すスクリーンショットです:

Pusher プライベートサブスクリプションフロー 

Delphi の例 

クライアントが Pusher サーバーに接続すると、Pusher が提供するキーを送信し、サーバーは識別 ID(socket_id)を返します。

クライアントがプライベート(またはプレゼンス)チャネルにサブスクライブする際、sgcWebSockets クライアントは Pusher が提供するシークレットキーを使用してサブスクリプションメッセージに含まれる署名を作成します。OnPusherAuthentication イベントを使用すると、メッセージの署名に必要なフィールドを取得し、独自の認証メソッドを実装できます。認証が成功した場合、署名を返すとその署名がサブスクリプションメッセージに含まれてサーバーに送信されます。

oClient := TsgcWebSocketClient.Create(nil);
oPusher := TsgcWSAPI_Pusher.Create(nil);
oPusher.Client := oClient;
oPusher.Cluster := 'eu'; 
Pusher.Name := 'js';
Pusher.Version := '4.1';
Pusher.TLS := True;
Pusher.Key := '9c3b7ef25qe97a00116c'; 
Pusher.Secret := ''; // the secret key is not known by the client, only by the authentication module
oPusher.OnPusherAuthentication := OnPusherAuthenticationEvent;
procedure OnPusherAuthenticationEvent(Sender: TObject; AuthRequest: TsgcWSPusherRequestAuthentication; AuthResponse: TsgcWSPusherResponseAuthentication);
begin
  // if the authentication request is succesful return the signature
  if CustomAuthentication(AuthRequest.Channel, AuthRequest.SocketID) then
    AuthResponse.Signature := GetCustomAuthenticationSignature;
end; 

署名のフォーマットは次のとおりです:

プライベートチャネル: key:HMAC256(SocketID, ChannelName)

プレゼンスチャネル: key: HMAC256(SocketID, ChannelName, Data)