SECRET OF CSS

Secure Custom Endpoints and Add Prometheus Metrics


A guide to better security

a keyboard and a padlock
Photo by FLY:D on Unsplash

The Spring Boot Actuator endpoints expose sensitive information about our app, such as Beans, measurements, etc. Therefore, it’s crucial to add security to restrict access.

Although the Actuator provides numerous endpoints out of the box, sometimes it can be useful to configure our own. For instance, if we want to retrieve information specific to our application.

Similarly, we might want to add Prometheus metrics to monitor features not included in the default solutions. For example, counting the number of visits to a URL, concurrent requests, etc.

By the end of this tutorial, you’ll know how to:

  • Secure Spring Boot Endpoints with Spring Security.
  • Create custom Spring Boot Actuator endpoints.
  • Register metrics and view them in Prometheus and Grafana.

This tutorial relates to my previous article about monitoring a Spring Boot application. If you want to learn how to set up Prometheus and Grafana to monitor your app check it out. But don’t worry, you can still follow this article because we’ll focus on different topics now.

Let’s get started!

I’ll reuse the source code of the previous demo and enhance it.

To enable security, we need to add the spring-boot-starter-security module to our dependencies:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

In the first of the project, we enabled the health metric available at http://localhost:8080/actuator/health and displayed the details to everyone:

Health endpoint with details

We can restrict access to the detailed information by changing this line in our application.yml file:

management.endpoint.health.show-details=WHEN_AUTHORIZED

If the user is not authorized, they will only see the following data:

{ “status”: “UP” }
Health information for unauthorized users

Add security credentials

Let’s say we want to permit access only for administrators. Add these lines to the application.yml to define a user:

security:
user:
name: user
password: password
roles: admin

Note that without these lines, Spring Boot will automatically generate a password and print it in the app’s console on startup. The role is optional.

Test the security config

  1. Hit the http://localhost:8080/actuator/health endpoint.
  2. You should see a pop-up window asking for credentials. Type in the details from the YAML file. You should be able to see the health details again.
  3. Change the role in the application.yml to something other than admin.
  4. Restart the app and hit the above URL again.
  5. You should only see the basic information without the details.

Add basic authentication

We can configure basic authentication using Spring Boot. To do so, create a configuration class like this:

Spring security config

We permitted the metrics endpoint to admin users only.

If we call the URL and try to log in with a different role, we’ll see an error message:

There was an unexpected error (type=Forbidden, status=403).

To add a custom endpoint, simply add the @Endpoint annotation to the class. Here is a simple example:

Spring Boot supports read, write and delete operations corresponding to the HTTP GET, POST, and DELETE requests.

In this example, we use the @ReadOperation annotation.

Let’s enable the endpoint in the application.yml:

include: [ "health","prometheus", "metrics", "customEndpoint" ]

Restart the application and try to access the new endpoint by hitting http://localhost:8080/actuator/customEndpoint.

Don’t be surprised if you see this error:

There was an unexpected error (type=Bad Request, status=400).

The reason is that we didn’t add a query parameter to the URL. The correct request should be http://localhost:8080/actuator/customEndpoint?id=1.

The result will return the fruit kiwi because it corresponds to number 1 in our fruitsMap.

Secure the endpoint

Now, let’s secure the custom endpoint. To do so, we just need to add it to our SecurityConfiguration.java class:

That’s it! It’s very simple to add and secure custom endpoints in Spring Boot!

Metric types overview

First, let’s take a look at the supported metrics:

  • Counter — used to measure events that increase. For example, the number of visits to a URL.
  • Gauges — used to measure values that can go up and down. For example, memory usage, temperature, etc.
  • Histogram — used to measure request duration and response size. The data is categorized into configurable buckets. Histograms expose the bucketed observation counts and the calculation of quantiles on the server side using the histogram_quantile() function.
  • Summary— used to track value distribution in percentiles. It’s similar to the Histogram metric. It uses the φ-quantile function on the client side and exposes the calculations directly.

Create a Counter metric

Let’s create a custom Counter metric to see how many times someone visited a URL from our app.

I’ll reuse the customEndpoint for the sake of simplicity. Here’s the code:

Here’s a code overview:

  • We added a Counter variable.
  • We increment the counter when someone visits the customEndpoint.
  • We registered the metric to the MeterRegistry.
  1. Visit http://localhost:8080/actuator/customEndpoint?id=1 two times.
  2. Open Prometheus and search for the new metric.
  3. You should see a similar result:
Counter result

Of course, you can also visualize the new metric in Grafana. It should look like this:

View the custom metric in Grafana.

If you’re wondering how to connect Grafana with Prometheus, check out the instructions in my previous tutorial.

You can use similar logic to register other metrics. The type depends on your use case. Check out the official documentation for more examples and usages.

In this tutorial, you learned how to create custom Spring Boot Actuator endpoints and secure them with Spring Security. Now you also know how to add custom metrics for Prometheus and view them using PromQL or Grafana.

You can find the complete source code for this demo in the References section below.

If you would like to explore the first part of this tutorial, you can find it here:

Thank you for reading, and happy coding!



News Credit

%d bloggers like this: