WebSocket

Service

websocket_service_jwt_auth.bal

import ballerina/websocket;

listener websocket:Listener securedEP = new (9090,
    secureSocket = {
        key: {
            certFile: "./resources/public.crt",
            keyFile: "./resources/private.key"
        }
    }
);

@websocket:ServiceConfig {
    auth: [
        {
            jwtValidatorConfig: {
                issuer: "wso2",
                audience: "ballerina",
                signatureConfig: {
                    certFile: "./resources/public.crt"
                },
                scopeKey: "scp"
            },
            scopes: ["admin"]
        }
    ]
}
isolated service /foo on securedEP {
    isolated resource function get bar() returns websocket:Service {
        return new WsService();
    }
}

isolated service class WsService {
    *websocket:Service;
    isolated remote function onTextMessage(websocket:Caller caller, string text) returns websocket:Error? {
        _ = check caller->writeTextMessage(text);
    }
}
$ bal run websocket_service_jwt_auth.bal

Client

websocket_client_self_signed_jwt_auth.bal

import ballerina/io;
import ballerina/websocket;

final websocket:Client wsClient = check new ("wss://localhost:9090/foo/bar",
    auth = {
        username: "ballerina",
        issuer: "wso2",
        audience: ["ballerina", "ballerina.org", "ballerina.io"],
        keyId: "5a0b754-895f-4279-8843-b745e11a57e9",
        jwtId: "JlbmMiOiJBMTI4Q0JDLUhTMjU2In",
        customClaims: { "scp": "admin" },
        expTime: 3600,
        signatureConfig: {
            config: {
                keyFile: "./resources/private.key"
            }
        }
    },
    secureSocket = {
        cert: "./resources/public.crt"
    }
);

public function main() returns error? {
    _ = check wsClient->writeTextMessage("Hello, World!");
    string response = check wsClient->readTextMessage();
    io:println(response);
}
$ bal run websocket_client_self_signed_jwt_auth.bal

Resources

public.crt

-----BEGIN CERTIFICATE-----
MIIDdzCCAl+gAwIBAgIEfP3e8zANBgkqhkiG9w0BAQsFADBkMQswCQYDVQQGEwJV
UzELMAkGA1UECBMCQ0ExFjAUBgNVBAcTDU1vdW50YWluIFZpZXcxDTALBgNVBAoT
BFdTTzIxDTALBgNVBAsTBFdTTzIxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0xNzEw
MjQwNTQ3NThaFw0zNzEwMTkwNTQ3NThaMGQxC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