Securing your Spring Boot API is essential to protect sensitive data and ensure that only authorized users can access your resources. Using OAuth2 combined with JWT (JSON Web Tokens) provides a robust security mechanism. This step-by-step tutorial guides you through the process of securing your Spring Boot API with OAuth2 and JWT.

Prerequisites

  • Java Development Kit (JDK) 11 or higher installed
  • Spring Boot 2.7.x or later
  • Basic knowledge of Spring Security
  • Postman or any API testing tool

Step 1: Create a New Spring Boot Project

Use Spring Initializr (https://start.spring.io/) to generate a new project with the following dependencies:

  • Spring Web
  • Spring Security
  • OAuth2 Resource Server
  • JWT

Download and unzip the project, then open it in your IDE.

Step 2: Configure Dependencies

Ensure your pom.xml includes the necessary dependencies for Spring Security and OAuth2 Resource Server:

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

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

Step 3: Configure Application Properties

In application.yml or application.properties, add the following configuration to specify your JWT issuer, audience, and the public key for token validation:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://your-authorization-server.com
          jwk-set-uri: https://your-authorization-server.com/.well-known/jwks.json

Step 4: Secure Your Endpoints

Create a security configuration class to specify which endpoints require authentication:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .oauth2ResourceServer()
                .jwt();
    }
}

Step 5: Obtain JWT Tokens

Use an OAuth2 authorization server to issue JWT tokens. Typically, you'll have an endpoint like /oauth/token where clients can request tokens by providing credentials.

Example request using Postman:

POST /oauth/token
Content-Type: application/x-www-form-urlencoded

grant_type=password&client_id=your-client-id&client_secret=your-client-secret&username=user&password=pass

The response will include an access_token which you will use to access protected endpoints.

Step 6: Test Your Secured API

Use the obtained JWT token in the Authorization header to access protected resources:

Authorization: Bearer your-jwt-token

Send requests to your API endpoints. If configured correctly, only requests with valid JWT tokens will succeed.

Conclusion

By following these steps, you can secure your Spring Boot API with OAuth2 and JWT. This setup ensures that only authenticated users with valid tokens can access your resources, enhancing your application's security.