Back to Examples

WebSocket service - JWT authentication

The websocket:Service and resource method can be secured with JWT and additionally, scopes can be added to enforce authorization. It validates the JWT sent in the Authorization header against the provided configurations. Ballerina uses the concept of scopes for authorization. The scope can be included in the JWT using a custom claim attribute. That custom claim attribute also can be configured as the scopeKey. In the authorization phase, the scopes of the service/resource are compared against the scope included in the JWT for at least one match between the two sets.

import ballerina/websocket;

listener websocket:Listener chatListener = new (9090,
    secureSocket = {
        key: {
            certFile: "../resource/path/to/public.crt",
            keyFile: "../resource/path/to/private.key"
        }
    }
);

// The service can be secured with JWT authentication and can be authorized
// optionally. JWT authentication can be enabled by setting the `websocket:JwtValidatorConfig` configurations.
// Authorization is based on scopes. A scope maps to one or more groups.
// Authorization can be enabled by setting the `string|string[]` type
// configurations for `scopes` field.
@websocket:ServiceConfig {
    auth: [
        {
            jwtValidatorConfig: {
                issuer: "wso2",
                audience: "ballerina",
                signatureConfig: {
                    certFile: "../resource/path/to/public.crt"
                },
                scopeKey: "scp"
            },
            scopes: ["admin"]
        }
    ]
}
service /chat on chatListener {

    resource function get .() returns websocket:Service {
        return new ChatService();
    }
}

service class ChatService {
    *websocket:Service;

    remote function onMessage(websocket:Caller caller, string chatMessage) returns error? {
        check caller->writeMessage("Hello, How are you?");
    }
}

Run the service by executing the command below.

$ bal run websocket_service_jwt_auth.bal

Tip: You can invoke the above service via the self-signed JWT authentication client.

Related Links

PreviousBasic authentication LDAP user store
NextOAuth2