<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[LearningPerk]]></title><description><![CDATA[LearningPerk]]></description><link>https://learningperk.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Wed, 18 Nov 2026 14:51:51 GMT</lastBuildDate><atom:link href="https://learningperk.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[From Zero to Secure: Implementing OAuth2 and JWT in a Kotlin Spring Boot App]]></title><description><![CDATA[Secure Kotlin Spring Boot APIs with OAuth2 and JWT. Beginner guide to authentication, authorization, scopes, roles, and token validation.]]></description><link>https://learningperk.hashnode.dev/from-zero-to-secure-implementing-oauth2-and-jwt-in-a-kotlin-spring-boot-app</link><guid isPermaLink="true">https://learningperk.hashnode.dev/from-zero-to-secure-implementing-oauth2-and-jwt-in-a-kotlin-spring-boot-app</guid><category><![CDATA[Kotlin]]></category><category><![CDATA[Security]]></category><dc:creator><![CDATA[Syed Ghufran Hassan]]></dc:creator><pubDate>Mon, 16 Nov 2026 20:58:44 GMT</pubDate><content:encoded><![CDATA[<h2>Introduction</h2>
<p>Building a REST API is one thing. Making sure that only the right people can access its resources is another challenge entirely.</p>
<p>As developers, we often spend most of our time designing endpoints, connecting databases, implementing business logic, and improving application performance. Security sometimes becomes an afterthought, especially when concepts like OAuth2, JWT, access tokens, and authorization scopes start appearing.</p>
<p>However, securing an API doesn't have to be complicated.</p>
<p>Two technologies that frequently work together in modern backend applications are <strong>OAuth2 and JSON Web Tokens (JWT)</strong>. Understanding how they complement each other can help you build APIs that are easier to maintain, scale, and protect.</p>
<p>In this article, we'll explore these concepts from a Kotlin developer's perspective and walk through how to configure a Spring Boot application as an OAuth2 Resource Server.</p>
<p>Let's start with the fundamentals.</p>
<ol>
<li><strong>Authentication and Authorization: Two Different Responsibilities</strong></li>
</ol>
<p>Before exploring OAuth2, it's important to understand two security concepts that are often confused.</p>
<p>Authentication: Verifying identity</p>
<p>Authentication establishes who is making a request.</p>
<p>For example, when a user signs in using their email and password, the application verifies their credentials to establish their identity.</p>
<p>Authorization: Controlling access</p>
<p>Authorization determines what an authenticated user is permitted to do.</p>
<p>For example:</p>
<ul>
<li>A regular user can view their own documents.</li>
<li>An administrator can access all documents.</li>
<li>A support agent can view documents but cannot delete them.</li>
</ul>
<p>An easy way to remember the distinction:</p>
<p>Authentication establishes identity; authorization determines permissions.</p>
<p>In a token-based system, authentication information and authorization-related claims can be carried inside an access token. The API uses these claims to make access-control decisions.</p>
<ol start="2">
<li><strong>Understanding OAuth2 Without the Complexity</strong></li>
</ol>
<p>OAuth2 is an authorization framework that allows applications to obtain limited access to protected resources without sharing the user's credentials with every application involved.</p>
<p>Consider an application where users sign in through an external identity provider.</p>
<p>Instead of asking every backend service to manage passwords, the application can delegate authentication and token issuance to a dedicated authorization server.</p>
<p>OAuth2 introduces four main roles:</p>
<p>Resource Owner: Usually the user who owns the protected information.</p>
<p>Client: The application requesting access to protected resources.</p>
<p>Authorization Server: The component responsible for issuing access tokens.</p>
<p>Resource Server: The API that receives requests and validates access tokens.</p>
<p>For backend developers, the Resource Server and Authorization Server are particularly important.</p>
<p>The Authorization Server issues tokens, while the Resource Server validates them before allowing access to protected endpoints.</p>
<p>This separation makes it possible to maintain multiple APIs without implementing a separate authentication mechanism in each one.</p>
<p>One important distinction: OAuth2 is primarily an authorization framework. When implementing user login, OpenID Connect (OIDC) is commonly used alongside OAuth2 to provide an identity layer.</p>
<ol start="3">
<li><strong>JWT: The Token That Carries Information</strong></li>
</ol>
<p>A JSON Web Token (JWT) is a compact format for representing claims that can be transmitted between systems.</p>
<p>A typical JWT looks like a long string containing three sections separated by periods:</p>
<p>`header.payload.signature`</p>
<p>Let's understand each component.</p>
<p><strong>Header</strong></p>
<p>Contains metadata about the token, such as its signing algorithm and token type.</p>
<p><strong>Payload</strong></p>
<p>Contains claims describing the token's subject and intended use.</p>
<p><strong>Example</strong></p>
<pre><code class="language-kotlin">{
  "sub": "user-123",
  "iss": "https://auth.example.com",
  "aud": ["documents-api"],
  "scope": "read:documents write:documents",
  "exp": 1893456000
}
</code></pre>
<p><strong>Signature</strong><br /><br />The signature allows the receiving application to verify that the token was issued by a trusted party and that its signed contents have not been modified.</p>
<p>A JWT is not automatically encrypted. Its payload can generally be decoded by anyone who possesses the token. Therefore, never store passwords, private keys, or other sensitive information in ordinary JWT claims.<br /><br /><strong>Why use JWT?</strong></p>
<p>One advantage of signed JWT access tokens is that a Resource Server can verify them locally using a trusted public key.</p>
<p>This can reduce the need for database lookups or calls to the Authorization Server on every API request.</p>
<p>It also supports stateless request authentication, where the server does not need to maintain a traditional login session for every client.</p>
<p>However, stateless authentication does not mean that token revocation is automatic. Short token lifetimes, key rotation, and appropriate revocation strategies are still important.<br /><br /><strong>4. Building a JWT-Protected API with Kotlin and Spring Boot</strong></p>
<p>Now let's move from concepts to implementation.</p>
<p>Imagine we're developing a document management API with two endpoints:</p>
<ul>
<li><code>GET /api/documents</code> — Retrieve documents.</li>
<li><code>POST /api/documents</code> — Create a document.</li>
</ul>
<p>We want authenticated users to access the API, but only users with the appropriate permissions should be able to retrieve or create documents.<br /><br /><strong>Step 1: Configure the Project</strong></p>
<p>Create a Spring Boot project with Kotlin and add the following dependencies:</p>
<ul>
<li>Spring Web</li>
<li>Spring Security</li>
<li>OAuth2 Resource Server</li>
</ul>
<p>For Gradle Kotlin DSL:</p>
<pre><code class="language-kotlin">dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.boot:spring-boot-starter-security")
    implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server")
}
</code></pre>
<p>We'll use an existing Authorization Server to issue JWT access tokens.</p>
<p>For local development, configure the Resource Server to trust the token issuer.<br /><br /><strong>Step 2: Create the Security Configuration</strong></p>
<p>Spring Security provides a Kotlin-friendly DSL that makes configuring HTTP security relatively straightforward.</p>
<p>Here's an example:</p>
<pre><code class="language-kotlin">@Configuration
@EnableWebSecurity
class SecurityConfiguration {

    @Bean
    fun securityFilterChain(
        http: HttpSecurity
    ): SecurityFilterChain {

        return http
            .csrf { it.disable() }
            .authorizeHttpRequests {
                it.requestMatchers(
                    HttpMethod.GET,
                    "/api/documents"
                ).hasAuthority("SCOPE_read:documents")

                it.requestMatchers(
                    HttpMethod.POST,
                    "/api/documents"
                ).hasAuthority("SCOPE_write:documents")

                it.anyRequest().authenticated()
            }
            .oauth2ResourceServer {
                it.jwt { }
            }
            .sessionManagement {
                it.sessionCreationPolicy(
                    SessionCreationPolicy.STATELESS
                )
            }
            .build()
    }
}
</code></pre>
<p>Let's examine what's happening.</p>
<ul>
<li><code>authorizeHttpRequests</code> defines which requests require specific permissions.</li>
<li><code>hasAuthority</code> checks whether the authenticated token provides the required authority.</li>
<li><code>oauth2ResourceServer</code> enables JWT-based authentication.</li>
<li><code>STATELESS</code> prevents Spring Security from creating traditional HTTP sessions.</li>
</ul>
<p>Notice that Spring Security automatically maps OAuth2 scope claims to authorities prefixed with <code>SCOPE_</code>.</p>
<p>For example, the scope <code>read:documents</code> becomes <code>SCOPE_read:documents</code>.</p>
<p>This allows us to protect individual endpoints without manually decoding JWTs inside controllers.</p>
<p>A production application should also configure CSRF according to its authentication architecture. Disabling CSRF is generally appropriate for a stateless API authenticated exclusively through bearer tokens in the Authorization header, but it should not be applied blindly to cookie-based authentication.</p>
<h3>Step 3: Create a Protected Controller</h3>
<p>With the security configuration in place, we can implement the document endpoints.</p>
<pre><code class="language-kotlin">@RestController
@RequestMapping("/api/documents")
class DocumentController {

    @GetMapping
    fun getDocuments(): String {
        return "List of available documents"
    }

    @PostMapping
    fun createDocument(): String {
        return "Document created successfully"
    }
}
</code></pre>
<p>The controller doesn't need to know how JWT verification works.</p>
<p>Spring Security handles authentication and authorization before the request reaches the controller.</p>
<p>This separation keeps business logic cleaner and easier to test.<br /><br /><strong>Step 4: Send an Authenticated Request</strong></p>
<p>Once your Authorization Server has issued an access token containing the required scope, you can test the protected endpoint.</p>
<p>For example:</p>
<pre><code class="language-bash">GET /api/documents HTTP/1.1
Host: localhost:8080
Authorization: Bearer YOUR_ACCESS_TOKEN
</code></pre>
<p>Spring Security validates the token before allowing the request to proceed.</p>
<p>The validation process includes checking the token's signature and standard claims such as expiration.</p>
<p>If the token is invalid or expired, the API rejects the request.</p>
<p>If authentication succeeds but the required scope is missing, Spring Security returns a forbidden response.<br /><br /><strong>5. Going Further: Custom Claims, Roles, and Permissions</strong></p>
<p>Scopes are useful, but real-world applications often require more detailed authorization rules.</p>
<p>Consider an application with three roles:</p>
<ul>
<li>ADMIN</li>
<li>EDITOR</li>
<li>VIEWER</li>
</ul>
<p>You might also want permissions such as:</p>
<ul>
<li><code>documents:read</code></li>
<li><code>documents:write</code></li>
<li><code>documents:delete</code></li>
</ul>
<p>These values can be included as custom claims in JWTs.<br /><br />For example:</p>
<pre><code class="language-kotlin">{
  "sub": "user-123",
  "scope": "read:documents",
  "roles": ["ADMIN", "EDITOR"],
  "permissions": [
    "documents:read",
    "documents:write"
  ]
}
</code></pre>
<p>Spring Security doesn't automatically interpret every custom claim as an authority.</p>
<p>To use these claims in access-control rules, we can implement a custom <code>JwtAuthenticationConverter</code>.</p>
<p>Here's a simplified Kotlin example:</p>
<pre><code class="language-kotlin">@Bean
fun jwtAuthenticationConverter(): JwtAuthenticationConverter {

    val converter = JwtGrantedAuthoritiesConverter()

    val jwtConverter = JwtAuthenticationConverter()

    jwtConverter.setJwtGrantedAuthoritiesConverter { jwt -&gt;

        val authorities = mutableListOf&lt;GrantedAuthority&gt;()

        authorities.addAll(
            converter.convert(jwt) ?: emptyList()
        )

        val roles = jwt.getClaimAsStringList("roles")
            ?: emptyList()

        roles.forEach { role -&gt;
            authorities.add(
                SimpleGrantedAuthority("ROLE_$role")
            )
        }

        authorities
    }

    return jwtConverter
}
</code></pre>
<p>You can then register this converter inside your Resource Server configuration:</p>
<pre><code class="language-kotlin">.oauth2ResourceServer {
    it.jwt { jwt -&gt;
        jwt.jwtAuthenticationConverter(
            jwtAuthenticationConverter()
        )
    }
}
</code></pre>
<p>Remember to enable method-level security using <code>@EnableMethodSecurity</code>.</p>
<p>This approach keeps authorization rules close to the operations they protect rather than spreading permission checks throughout your application.<br /><br /><strong>6. Don't Forget Issuer and Audience Validation</strong></p>
<p>Verifying a JWT signature is important, but signature verification alone should not be your entire security strategy.</p>
<p>Two additional claims deserve attention:</p>
<p><strong>Issuer (</strong><code>iss</code><strong>)</strong></p>
<p>Identifies the entity that issued the token.</p>
<p>Your API should only accept tokens from an expected, trusted issuer.</p>
<p><strong>Audience (</strong><code>aud</code><strong>)</strong></p>
<p>Identifies the intended recipient of the token.</p>
<p>For example, a token issued for a payment API should not automatically be accepted by a document management API.</p>
<p>Spring Security supports issuer validation through its JWT configuration. Audience validation can be added using an appropriate <code>OAuth2TokenValidator</code>.</p>
<p>A simplified example:</p>
<pre><code class="language-kotlin">@Bean
fun jwtDecoder(): JwtDecoder {

    val decoder = JwtDecoders.fromIssuerLocation(
        "https://auth.example.com"
    ) as NimbusJwtDecoder

    val audienceValidator = OAuth2TokenValidator&lt;Jwt&gt; { jwt -&gt;

        if (jwt.audience.contains("documents-api")) {
            OAuth2TokenValidatorResult.success()
        } else {
            OAuth2TokenValidatorResult.failure(
                OAuth2Error(
                    "invalid_token",
                    "Invalid audience",
                    null
                )
            )
        }
    }

    decoder.setJwtValidator(
        DelegatingOAuth2TokenValidator(
            JwtValidators.createDefaultWithIssuer(
                "https://auth.example.com"
            ),
            audienceValidator
        )
    )

    return decoder
}
</code></pre>
<p>This example combines the standard issuer and timestamp validations with an application-specific audience check.</p>
<p>The result is a Resource Server that accepts tokens only when they meet the expected trust requirements.<br /><br /><strong>7. Security Practices Worth Following</strong></p>
<p>Before deploying your API, keep these practical considerations in mind:</p>
<ol>
<li><strong>Use HTTPS:</strong> Never transmit bearer tokens over unencrypted connections.</li>
<li><strong>Keep access tokens short-lived:</strong> Reduce the exposure window if a token is compromised.</li>
<li><strong>Protect signing keys:</strong> Private signing keys should remain with the trusted issuer.</li>
<li><strong>Validate the audience:</strong> Make sure tokens are intended for your API.</li>
<li><strong>Apply least privilege:</strong> Give users only the scopes and permissions they actually need.</li>
<li><strong>Avoid sensitive JWT claims:</strong> Remember that signed JWT payloads are not encrypted.</li>
<li><strong>Plan for key rotation:</strong> Your Resource Server should trust the appropriate current signing keys.</li>
<li><strong>Consider revocation:</strong> Stateless JWT validation does not automatically invalidate a token before its expiration.</li>
</ol>
<p>These practices help turn a working authentication implementation into a more reliable security architecture.</p>
<h2>Conclusion</h2>
<p>OAuth2 and JWT can initially seem like complicated topics, particularly when you're encountering them for the first time in a backend project.</p>
<p>But once you understand the responsibilities of each component, the architecture becomes much easier to follow.</p>
<p>OAuth2 provides the authorization framework, the Authorization Server issues access tokens, JWT carries signed claims, and Spring Security validates those tokens before granting access to protected resources.</p>
<p>Kotlin makes the implementation approachable through its concise syntax, null-safety features, and Spring Security DSL.</p>
<p>The best way to understand these technologies is to build something small, configure a Resource Server, issue a token with specific scopes, and experiment with different authorization rules.</p>
<p>API security isn't just about preventing unauthorized requests. It's about building applications that users and developers can trust. You can read more about the tutorial <a href="https://blog.jetbrains.com/kotlin/2026/07/secure-your-apis-oauth2-and-jwt-for-beginners/?utm_source=blog&amp;utm_medium=referral&amp;utm_campaign=influencer_distribution&amp;utm_content=kotlin_oauth2_jwt">here</a></p>
<p><strong>Happy securing!</strong></p>
]]></content:encoded></item></channel></rss>