Introduction
If you have ever built a REST API, you know that security is rarely the fun part. It is, however, the part that keeps your users' data safe and your application trustworthy. For a long time, I avoided diving into OAuth2 and JWT because the terminology felt like a wall I could not climb. Recently, I came across a beginner-friendly guide by Mdu Sibisi on the JetBrains Kotlin blog, and it finally made these concepts click. This post is my own take on that material—a distilled, practical overview for Kotlin developers who want to secure their Spring Boot APIs without getting lost in the theory.
Authentication vs. Authorization: The Core Distinction
Before touching any code, you need to internalize the difference between these two terms, because conflating them is the root of much confusion.
Authentication answers: Who are you? It is about verifying identity, usually through credentials like a password, a certificate, or a token.
Authorization answers: What are you allowed to do? It is about permissions, scopes, and roles.
In an OAuth2 + JWT system, think of the JWT as your ID card (authentication) and the scopes/roles inside it as the list of rooms your badge unlocks (authorization). OAuth2 is the framework that manages how that badge gets issued and checked
The Four Roles in OAuth2 (You Only Need to Remember Two)
OAuth2 defines four roles, but for a backend API developer, the two most important ones are:
Resource Server: This is your API. It hosts the protected data and validates incoming tokens. It does not issue tokens; it only checks them.
Authorization Server: This is the server that issues tokens after authenticating the user.
The beauty of this separation is that your API (the Resource Server) can stay lean. It does not need to handle login forms, password storage, or session management. It simply trusts tokens that are signed by the Authorization Server
What Exactly Is a JWT?
A JSON Web Token (JWT) is a compact, URL-safe string that carries information (called claims) between systems. It has three parts, separated by dots:
Header: Metadata about the token, such as the signing algorithm (e.g., HS256 or RS256).
Payload: The claims—user ID, roles, permissions, expiration time, and any custom data you need.
Signature: A cryptographic seal that allows the recipient to verify the token has not been tampered with.
Because the token is self-contained and signed, the Resource Server can validate it without a database lookup. This enables stateless authentication, which reduces infrastructure complexity and improves performance
Implementing OAuth2 and JWT in a Kotlin Spring Boot API
The original tutorial builds a simple document management API with endpoints like GET /documents and POST /documents. Here is a streamlined version of the implementation steps.
Step 1: Project Setup
Create a Spring Boot project with Kotlin and include these dependencies:
- Spring Security
- OAuth2 Authorization Server
- OAuth2 Resource Server
- Spring Web
In your application.properties, point the Resource Server to a public key for JWT verification:
spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public.pem
In a real application, you would use an issuer-uri to let Spring discover the Authorization Server's configuration automatically. For learning purposes, a locally generated key pair (public/private) is sufficient.
Step 2: Configure the Resource Server
The security configuration in Kotlin is remarkably clean thanks to the DSL. Here is a minimal SecurityFilterChain that enforces JWT authentication and checks for a required scope:
@Configuration
@EnableWebSecurity
class OAuth2ResourceServerSecurityConfiguration {
@Bean
fun securityFilterChain(http: HttpSecurity): SecurityFilterChain = http
.httpBasic { it.disable() }
.formLogin { it.disable() }
.csrf { it.disable() }
.authorizeHttpRequests {
it.requestMatchers(HttpMethod.GET, "/api/fetchDocuments")
.hasAuthority("SCOPE_read:documents")
it.anyRequest().authenticated()
}
.oauth2ResourceServer { it.jwt { } }
.sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) }
.build()
}
This configuration does three critical things: it disables session-based state, enables JWT validation, and requires the read:documents scope for the GET endpoint
Step 3: Generate and Test a JWT
To test the endpoint, generate a JWT using the private key, sign it with RS256, and include the necessary claims. Then send a request:
GET http://localhost:8080/api/fetchDocuments
Authorization: Bearer <your-jwt-here>
If the token is valid and carries the correct scope, you will receive the protected resource. The Resource Server automatically checks the signature and expiration before granting access.
Moving Beyond Basics: Custom Claims and Fine-Grained Authorization
Scope-based checks are a good start, but real-world applications often need role-based and permission-based control. JWTs can carry custom claims like roles and permissions.
However, Spring Security does not automatically map custom role claims to authorities because there is no universal standard for how identity providers represent roles. You need a custom JwtAuthenticationConverter to extract scopes, roles, and permissions from the token and convert them into Spring GrantedAuthority objects.
Kotlin's null-safety features make this extraction remarkably robust. The safe call operator (?.), safe cast (as?), and Elvis operator (?:) allow you to handle missing or malformed claims gracefully without risking NullPointerException or ClassCastException.
Once the claims are mapped, you can use @PreAuthorize for method-level security:
@GetMapping("/fetchDocuments")
@PreAuthorize("hasRole('admin') and hasAuthority('documents:read:all')")
fun fetchDocumentsEndpoint(): String {
return "Here are your documents"
}
This keeps security logic out of your controller bodies and makes the rules declarative and maintainable.
Strengthening Token Trust: Issuer and Audience Validation
Even with signature verification, you should explicitly validate the iss (issuer) and aud (audience) claims. This prevents token replay attacks and ensures that a token meant for a different application is not accepted by your API.
While Spring provides a default issuer validator, audience validation often requires a custom OAuth2TokenValidator. You can compose multiple validators using DelegatingOAuth2TokenValidator and attach them to a custom JwtDecoder. This is a small amount of extra code that significantly hardens your security posture.
Key Takeaways for Kotlin Developers
- OAuth2 and JWT are complementary: OAuth2 handles delegated authorization, while JWT is the token format that carries the claims.
- Resource Servers should stay stateless: Let the Authorization Server handle token issuance; your API only validates.
- Kotlin's DSL and null-safety are a natural fit: The Spring Security Kotlin DSL reduces boilerplate, and Kotlin's safe operators make claim extraction safe and concise.
- Layer your defenses: Combine scopes, roles, and custom validators (issuer + audience) to achieve fine-grained, context-aware authorization.
If you have been putting off API security because it felt intimidating, I encourage you to start with a small project and follow the steps above. The concepts become much clearer once you see a token flow end-to-end. For the full, detailed walkthrough, the original JetBrains tutorial is an excellent reference. You can access it here
Happy Securing !
Top comments (0)