Back to Examples

gRPC service - OAuth2

A gRPC service 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 metadata 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 are compared against the scope included in the introspection response for at least one match between the two sets.

import ballerina/grpc;

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

@grpc: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"]
        }
    ]
}
@grpc:Descriptor {
    value: GRPC_SIMPLE_DESC
}
service "HelloWorld" on securedEP {

    remote function hello(string request) returns string {
        return "Hello " + request;
    }
}

Setting up the service is the same as setting up the simple RPC service with additional configurations. For information on implementing the service, see gRPC service - Simple RPC.

Run the service by executing the command below.

$ bal run service

Tip: You can invoke the above service via the clients below.

Related links

PreviousJWT authentication
NextSSL/TLS