blog

Integrating Grafana with JWT Authentication in Java Applications

When it comes to building modern applications, especially in distributed systems, it is imperative to have a robust authentication mechanism in place. JWT (JSON Web Token) has emerged as a popular choice for securing APIs alongside traditional methods. In this article, we will explore how to integrate Grafana with JWT authentication in Java applications while ensuring API security, leveraging IBM API Connect, and utilizing the API Open Platform. Let’s dive into it!

Understanding the Importance of API Security

API security is a crucial aspect of modern application development. With the increase in APIs and their critical role in connecting applications and services, securing them against unauthorized access is paramount. In a world where data breaches are common, implementing secure authentication methods like JWT can help safeguard your applications.

The Role of JWT in API Authentication

JWT is an open standard that defines a compact way to securely transmit information between parties. It consists of three parts: the header, the payload, and the signature. The payload can include user roles, privileges, and any other claims you want to include in the token.

  1. Header: Typically consists of two parts: the type of the token (JWT) and the signing algorithm being used, such as HMAC SHA256 or RSA.

  2. Payload: Contains the claims. Claims are statements about an entity (typically, the user) and additional data.

  3. Signature: To create the signature part, you take the encoded header, the encoded payload, a secret, and sign it using the algorithm specified in the header.

Here is how a JWT looks:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ
SflKxwVZcrNPQX8uP4cVhdfQ6TZNiG7kp2q0friends9ye-aTo9whijw

The ability to embed claims related to the user makes JWT a flexible and powerful tool for authentication in APIs.

Benefits of Integration: IBM API Connect & API Open Platform

Integrating with IBM API Connect allows developers to manage and secure APIs efficiently. The IBM API Connect is designed to support the complete API lifecycle—from creation to retirement, making it a reliable choice for organizations.

The benefits of using IBM API Connect include:
API gateway: Provides a single entry point for API requests.
Security policies: Ensures all APIs are secure through various authentication and authorization methods.
Analytics: Monitors API usage and performance metrics.

The API Open Platform is where APIs thrive. It is a set of protocols and tools that facilitate the creation, deployment, and consumption of APIs. This integration enables organizations to manage API documentation effectively, ensuring that all API consumers have access to the necessary information.

Setting Up Grafana for JWT Authentication

Grafana is an open-source platform for monitoring and observability, allowing you to visualize and analyze data. Here’s how we can set it up to use JWT authentication.

Prerequisites

Before we begin, make sure you have:
– A running Java application (Spring Boot preferred).
– Grafana up and running.
– IBM API Connect configured with your JWT settings.
– Basic understanding of Spring Security.

Step 1: Including Necessary Dependencies

Firstly, you will want to include relevant dependencies in your pom.xml. For JWT, you may want to include:

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.1</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Step 2: Configuring JWT in Java Application

You will want to create a utility class to manage JWT tokens. Below is an example of how this might look:

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtil {

    private String secret = "your_secret_key"; // This should be an environment variable

    public String generateToken(String username) {
        Map<String, Object> claims = new HashMap<>();
        return createToken(claims, username);
    }

    private String createToken(Map<String, Object> claims, String subject) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) // token valid for 10 hours
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
    }

    public boolean validateToken(String token, String username) {
        final String extractedUsername = extractUsername(token);
        return (extractedUsername.equals(username) && !isTokenExpired(token));
    }

    public String extractUsername(String token) {
        return extractAllClaims(token).getSubject();
    }

    private Claims extractAllClaims(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    private boolean isTokenExpired(String token) {
        return extractAllClaims(token).getExpiration().before(new Date());
    }
}

Step 3: Configuring Spring Security

You can integrate JWT into Spring Security as follows. You will need a security configuration class:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtRequestFilter jwtRequestFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/authenticate").permitAll() // use this for login endpoint
            .anyRequest().authenticated();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

Make sure to include a JwtRequestFilter to validate the incoming requests:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationFilter;

public class JwtRequestFilter extends WebAuthenticationFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        final String authorizationHeader = request.getHeader("Authorization");

        String username = null;
        String jwt = null;

        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
            username = jwtUtil.extractUsername(jwt);
        }

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            // Validate the token here and set Authentication
        }
        chain.doFilter(request, response);
    }
}

APIPark is a high-performance AI gateway that allows you to securely access the most comprehensive LLM APIs globally on the APIPark platform, including OpenAI, Anthropic, Mistral, Llama2, Google Gemini, and more.Try APIPark now! 👇👇👇

Step 4: Configuring Grafana to Use JWT Tokens

Now that we have set up JWT authentication in our Java application, it is time to configure Grafana to use JWT tokens for authentication.

Grafana does not support JWT out of the box but offers a way to use a reverse proxy. You can set up NGINX or any proxy server in front of Grafana to handle the JWT tokens.

Here’s an example NGINX configuration:

server {
    listen 80;

    location / {
        proxy_pass http://localhost:3000; # Grafana's default port
        proxy_set_header Host $host;
        proxy_set_header X-real-IP $remote_addr;

        # JWT validation logic
        auth_jwt "Closed Site";
        auth_jwt_key_file /etc/nginx/jwt.key; # Points to your public key
    }
}

This setup would allow NGINX to validate JWTs before proxying the requests to Grafana.

Step 5: Testing the Setup

After completing the configurations, you should be able to test your setup. Here are the steps you might follow:

  1. Generate JWT Token: You should have an endpoint in your Java application to authenticate users and retrieve a JWT token.

  2. Access Grafana via Token: Now, access Grafana through your reverse proxy. You should include the JWT token in the Authorization header.

For example, using cURL:

curl -H "Authorization: Bearer <your_jwt_token>" http://<nginx_server_address>

You should now have access to Grafana dashboard, assuming the token is valid.

Summary

In conclusion, integrating Grafana with JWT authentication in your Java applications enhances the security of your APIs. By using this approach, businesses can leverage the robustness of JWT alongside the powerful API management capabilities offered by IBM API Connect.

Implementing an effective API documentation management strategy in conjunction with this integration will further facilitate developer onboarding and usage tracking.

Here is a table summarizing the tools and technologies discussed:

Tool/Technology Purpose
JWT Secure token-based authentication
Spring Boot Framework for building Java applications
IBM API Connect API management and security
Grafana Data visualization and monitoring
NGINX Reverse proxy for handling requests

Ensure your applications are secure by adopting best practices in API security, and consider the tips discussed here when integrating Grafana with JWT authentication in Java. This approach not only protects your data but also enhances collaborative workflows in a secure environment.

🚀You can securely and efficiently call the Gemni API on APIPark in just two steps:

Step 1: Deploy the APIPark AI gateway in 5 minutes.

APIPark is developed based on Golang, offering strong product performance and low development and maintenance costs. You can deploy APIPark with a single command line.

curl -sSO https://download.apipark.com/install/quick-start.sh; bash quick-start.sh

APIPark Command Installation Process

In my experience, you can see the successful deployment interface within 5 to 10 minutes. Then, you can log in to APIPark using your account.

APIPark System Interface 01

Step 2: Call the Gemni API.

APIPark System Interface 02