In this article, we’ll take a look at building a secured REST API by integrating with Okta as the identity provider via OpenID Connect (OIDC). This article is based on the DZone article Building a Java REST API with Quarkus, which explains how to create a Java REST API with Quarkus and Okta. We will be implementing a similar scenario here by using Ballerinalang, and show how it’s simpler and more straightforward to implement compared to our Java counterpart.
Let’s start off by creating a simple hello world service application as our base scenario. Add the following code to a file named hello.bal.
Listing 1:_ Hello World Service_
The above service can be run by using the following command:
Shell
$ ballerina run hello.bal
[ballerina/http] started HTTP/WS listener 0.0.0.0:8080
The final source code of our hello world service can be found here.
Let’s invoke the service by sending a request.
Shell
$ curl http://localhost:8080/secured/hello
Hello Anonymous, authScheme: N/A
Here, the service is invoked through HTTP without any form of user authentication.
Let’s update our hello world service in order to authenticate users who invoke it using a JWT.
Listing 2:_ Secured Hello World Service with JWT_
We have done several new things to our earlier service implementation. First, our HTTP listener that was bound to the service construct HelloService has been changed from new http:Listener(8080) to httpsListener. Earlier we created an anonymous HTTP listener object in place, and now, we have created a separate HTTPS listener object and referred to it from the service. This approach is required when we want to provide additional configurations to the listener compared to the inline creation. A Ballerina service is not limited to having only one listener, but it can have multiple compatible listeners attached to a single service at a time. The listener object simply needs to be given as a comma-separated list.
HTTP listener objects provide the functionality to associate a set of authentication and authorization providers. In our case, we have created a single JWT inbound auth provider and registered as an auth handler in the HTTPS listener configuration. In Ballerina, it is mandated that a secure transport should be used in an authentication scenario such as in our case. This is where a bearer token is sent through the headers and would be susceptible to a man-in-the-middle attack if a secured protocol is not used.
Figure 1 shows a summary of the relationship between the Ballerina services, listeners, and authentication providers.
#security #tutorial #rest api #microservice #okta #ballerina #open id connect