Back to Examples

WebSocket service - OAuth2

The websocket:Service and resource method can be secured with OAuth2 and additionally, scopes can be added to enforce fine-grained authorization. It validates the OAuth2 token sent in the Authorization header against the provided configurations. This calls the configured introspection endpoint to validate. Ballerina uses the concept of scopes for authorization. The scope can be included in the introspection response 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 introspection response 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 OAuth2 and by enforcing authorization
// optionally. It can be enabled by setting the `websocket:OAuth2IntrospectionConfig` 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: [
        {
            oauth2IntrospectionConfig: {
                url: "https://localhost:9445/oauth2/introspect",
                tokenTypeHint: "access_token",
                scopeKey: "scp",
                clientConfig: {
                    customHeaders: {"Authorization": "Basic YWRtaW46YWRtaW4="},
                    secureSocket: {
                        cert: "../resource/path/to/public.crt"
                    }
                }
            },
            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_oauth2.bal

Tip: You can invoke the above service via the OAuth2 JWT Bearer grant type client.

Related Links

PreviousJWT authentication
NextSSL/TLS