Samitha Chathuranga
Samitha Chathuranga

Reputation: 1749

How to write Introspection server with ballerina

I can find a guide in "Learn by Example" how to Secure a Service with OAuth2 [1]. This example uses a separate introspection server as below.

oauth2:InboundOAuth2Provider oauth2Provider = new ({
    url: "https://localhost:9095/oauth2/token/introspect"
});

So is there any guide/article I can use to follow to implement an introspection server, so that I can write a complete OAuth2 scenario to secure my ballerina service with OAuth2?

[1] https://ballerina.io/v1-2/learn/by-example/secured-service-with-oauth2.html

Upvotes: 2

Views: 101

Answers (1)

Chanaka Lakmal
Chanaka Lakmal

Reputation: 1122

You can implement your own OAuth2 introspection server according to the instructions given by the RFC https://www.rfc-editor.org/rfc/rfc7662.

A draft implementation can be found below. You have to extract and validate the received token agains the issued access tokens by the server.

import ballerina/config;
import ballerina/http;

listener http:Listener oauth2Server = new(9095, {
    secureSocket: {
        keyStore: {
            path: config:getAsString("keystore"),
            password: config:getAsString("keystorePassword")
        }
    }
});

service oauth2 on oauth2Server {

    @http:ResourceConfig {
        methods: ["POST"],
        path: "/token/introspect"
    }
    // This introspect the access token against the access token store, 
    // which holds the issued access tokens.
    resource function introspect(http:Caller caller, http:Request req) {
        http:Response res = new;
        var authorizationHeader = trap req.getHeader("Authorization");
        if (authorizationHeader is string) {
            // Validate the received authorization header and 
            // prepare the introspection response. 
            // (Refer: https://www.rfc-editor.org/rfc/rfc7662#section-2.2)
            res = ...;
        } else {
            // Invalid client. 
            // (Refer: https://www.rfc-editor.org/rfc/rfc6749#section-5.2)
            res.statusCode = 401;
            res.setPayload("invalid_client");
        }
        checkpanic caller->respond(res);
    }
}

Upvotes: 2

Related Questions