import ballerina/http;
import ballerina/log;

// Defines the HTTP client to call the OAuth2 secured APIs.
// The client is enriched with the `Authorization: Bearer <token>` header by
// passing the `http:RefreshTokenGrantConfig` for the `auth` configuration of the
// client.
http:Client securedEP = check new("https://localhost:9090", {
    auth: {
        refreshUrl: "https://localhost:9090/oauth2/token/refresh",
        refreshToken: "tGzv3JOkF0XG5Qx2TlKWIA",
        clientId: "s6BhdRkqt3",
        clientSecret: "7Fjfp0ZBr1KtDRbnfVdmIw",
        scopes: ["hello"],
        clientConfig: {
            secureSocket: {
                cert: "../resource/path/to/public.crt"
            }
        }
    },
    secureSocket: {
        cert: "../resource/path/to/public.crt"
    }
});

public function main() {
    // Send a `GET` request to the specified endpoint.
    var response = securedEP->get("/foo/bar");
    if (response is http:Response) {
        log:printInfo(response.statusCode.toString());
    } else {
        log:printError("Failed to call the endpoint.", 'error = response);
    }
}

HTTP Client with OAuth2 Refresh Token Grant Type

A client, which is secured with an OAuth2 refresh token grant type can be used to connect to a secured service.
The client is enriched with the Authorization: Bearer <token> header by passing the http:OAuth2RefreshTokenGrantConfig to the auth configuration of the client.

For more information on the underlying module, see the OAuth2 module.

import ballerina/http;
import ballerina/log;
http:Client securedEP = check new("https://localhost:9090", {
    auth: {
        refreshUrl: "https://localhost:9090/oauth2/token/refresh",
        refreshToken: "tGzv3JOkF0XG5Qx2TlKWIA",
        clientId: "s6BhdRkqt3",
        clientSecret: "7Fjfp0ZBr1KtDRbnfVdmIw",
        scopes: ["hello"],
        clientConfig: {
            secureSocket: {
                cert: "../resource/path/to/public.crt"
            }
        }
    },
    secureSocket: {
        cert: "../resource/path/to/public.crt"
    }
});

Defines the HTTP client to call the OAuth2 secured APIs. The client is enriched with the Authorization: Bearer <token> header by passing the http:RefreshTokenGrantConfig for the auth configuration of the client.

public function main() {
    var response = securedEP->get("/foo/bar");
    if (response is http:Response) {
        log:printInfo(response.statusCode.toString());
    } else {
        log:printError("Failed to call the endpoint.", 'error = response);
    }
}

Send a GET request to the specified endpoint.

# Before test this sample, first start a sample service secured with OAuth2.
# To run this sample, navigate to the directory that contains the `.bal` file,
# and execute the `bal run` command below.
# (You may need to change the trusted certificate file path.)
bal run http_client_with_oauth2_refresh_token_grant_type.bal
time = 2021-01-20 20:04:13,261 level = INFO  module = "" message = "200"