docs / articles / Java REST API Key Authentication Example

Java REST API Key Authentication Example

Sara Jul 09, 2026 2026-07-09 04:40:45

In the realm of web development, REST APIs have become the backbone of communication between servers and clients. One crucial aspect of securing these APIs is authentication, which ensures that only authorized users can access and manipulate resources. Java, being a popular language for backend development, provides several ways to implement API key authentication in REST services. Let's delve into an example using Spring Security and JWT (JSON Web Tokens).

the rest api application is shown in this diagram, which shows how to use rest apis
the rest api application is shown in this diagram, which shows how to use rest apis

Before we dive into the implementation, let's understand why API key authentication is important. It helps prevent unauthorized access, data breaches, and misuse of your API. By requiring a unique key for each user or client, you can control and monitor who is accessing your API and what actions they are performing.

#restapi #backenddevelopment #apidesign #webdevelopment #programmingtips… | Mohammed Surguli | 17 comments
#restapi #backenddevelopment #apidesign #webdevelopment #programmingtips… | Mohammed Surguli | 17 comments

Setting Up the Project and Dependencies

To get started, we'll use Spring Boot for our Java REST API. First, add the following dependencies to your build.gradle or pom.xml file:

Implementing API Key Authentication in ASP.NET Core
Implementing API Key Authentication in ASP.NET Core

  • spring-boot-starter-web - For creating the REST API
  • spring-boot-starter-security - For Spring Security features
  • io.jsonwebtoken - For JSON Web Token handling

Creating the API Endpoint

REST API Basics with Express.js — How Endpoints Are Structured
REST API Basics with Express.js — How Endpoints Are Structured

Let's create a simple REST controller with an endpoint that requires authentication:

@RestController
@RequestMapping("/api")
public class AuthController {

    @GetMapping("/protected")
    public ResponseEntity<String> getProtectedData(@AuthenticationPrincipal JwtPrincipal principal) {
        return new ResponseEntity<;"Hello, " + principal.getUsername() + "!", HttpStatus.OK);
    }
}

This endpoint, /api/protected, will return a personalized greeting once the user is authenticated.

🔥 5 Key Concepts in Java You Should Master! 🧠
🔥 5 Key Concepts in Java You Should Master! 🧠

Configuring Spring Security

Now, let's configure Spring Security to use JWT for authentication. Create a SecurityConfig class:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeRequests().anyRequest().authenticated();
    }

    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() {
        return new JwtAuthenticationFilter(authenticationManager());
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(new JwtAuthenticationProvider());
    }
}

What is API and REST APIs? – In easy language
What is API and REST APIs? – In easy language

In this configuration, we're disabling CSRF protection, setting the session management strategy to STATELESS, and requiring authentication for all requests.

Implementing JWT Authentication

HashMap vs HashSet in Java ⚡ Key Differences Explained (DSA Cheat Sheet)
HashMap vs HashSet in Java ⚡ Key Differences Explained (DSA Cheat Sheet)
HTTP Methods - REST API Tutorial
HTTP Methods - REST API Tutorial
How API Requests Work in Next.js (Visual Guide for Developers)
How API Requests Work in Next.js (Visual Guide for Developers)
Building a full-stack app with React? Your backend needs to be just as clean as your frontend.
Building a full-stack app with React? Your backend needs to be just as clean as your frontend.
Exception Handling in Java | Try Catch Finally Explained with Example
Exception Handling in Java | Try Catch Finally Explained with Example
Java 8 Streams API - findAny, findFirst methods tutorial with examples
Java 8 Streams API - findAny, findFirst methods tutorial with examples
☕ Java Basics Cheat Sheet for Beginners | Learn Java in One Page 🚀
☕ Java Basics Cheat Sheet for Beginners | Learn Java in One Page 🚀
Top Features of Java Every Beginner Should Know ☕🚀
Top Features of Java Every Beginner Should Know ☕🚀
Java road maps
Java road maps
an image of a computer screen with text
an image of a computer screen with text
Java Collection Framework: ArrayList Explained Visually
Java Collection Framework: ArrayList Explained Visually
Keywords in JAVA
Keywords in JAVA
an info sheet with some information about the language and its meaning, including instructions for using it
an info sheet with some information about the language and its meaning, including instructions for using it
Java Stream API
Java Stream API
a poster with an image of a programming program
a poster with an image of a programming program
Interface in Java
Interface in Java
Java Streams Cheat Sheet. Creation, Intermediate & Terminal Operations (Java 17+)
Java Streams Cheat Sheet. Creation, Intermediate & Terminal Operations (Java 17+)
Java Switch Example
Java Switch Example
Do My Java Assignment? Here's What Actually Works for CS Students at 2 AM
Do My Java Assignment? Here's What Actually Works for CS Students at 2 AM
a table that has two different types of content and text on it, with the words in
a table that has two different types of content and text on it, with the words in

To handle JWT authentication, we'll create a JwtAuthenticationProvider class:

public class JwtAuthenticationProvider extends AbstractAuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String token = (String) authentication.getPrincipal();
        if (JwtTokenUtil.isTokenValid(token)) {
            String username = JwtTokenUtil.getUsernameFromToken(token);
            return new UsernamePasswordAuthenticationToken(username, null, List.of(new SimpleGrantedAuthority("ROLE_USER")));
        } else {
            throw new BadCredentialsException("Invalid token");
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return JwtAuthenticationToken.class.isAssignableFrom(authentication);
    }
}

This provider checks if the provided token is valid and extracts the username from it. If the token is valid, it returns a UsernamePasswordAuthenticationToken with the extracted username.

Generating and Verifying JWT Tokens

Create a JwtTokenUtil class to handle token generation and verification:

public class JwtTokenUtil {

    private static final long EXPIRATION_TIME = 86400000; // 1 day
    private static final String SECRET_KEY = "your_secret_key";

    public static String generateToken(String username) {
        return Jwts.builder()
            .setSubject(username)
            .setIssuedAt(new Date())
            .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
            .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
            .compact();
    }

    public static boolean isTokenValid(String token) {
        try {
            Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
            return true;
        } catch (MalformedJwtException e) {
            log.error("Invalid JWT token: {}", e.getMessage());
        } catch (ExpiredJwtException e) {
            log.error("JWT token is expired: {}", e.getMessage());
        } catch (UnsupportedJwtException e) {
            log.error("JWT token is unsupported: {}", e.getMessage());
        } catch (IllegalArgumentException e) {
            log.error("JWT claims string is empty: {}", e.getMessage());
        }
        return false;
    }

    public static String getUsernameFromToken(String token) {
        Claims claims = Jwts.parser()
            .setSigningKey(SECRET_KEY)
            .parseClaimsJws(token)
            .getBody();
        return claims.getSubject();
    }
}

This utility class generates JWT tokens with a specified expiration time and verifies the authenticity of tokens using the secret key.

With these implementations, you now have a REST API with API key authentication using JWT in Java. Users must provide a valid token in the Authorization header to access the protected endpoint. Keep in mind that in a real-world application, you should store user credentials securely and generate tokens only after successful authentication.

In the world of REST APIs, security is paramount. By implementing API key authentication, you're taking a significant step towards protecting your application and its users. As your API evolves, consider exploring other security measures like rate limiting, input validation, and secure communication protocols to further fortify your API. Happy coding!