OAuth 2.0 and JWT Authorization in Kotlin: For Beginners
Modern web applications and APIs rarely function without an authentication and authorization system. The two most popular standards in this area are OAuth 2.0 and JWT (JSON Web Token). In this article, we will cover how to implement authorization in Kotlin using these technologies. The material is intended for beginner developers familiar with the basics of the language and the Spring Boot framework.
What are OAuth 2.0 and JWT?
Before writing code, it is important to understand the theory.
OAuth 2.0 is an authorization protocol that allows applications to obtain limited access to user resources without transmitting a login and password. Imagine logging into a website via "Sign in with Google" — that is OAuth 2.0.
JWT is a compact and self-contained token format. It consists of three parts: header, payload, and signature. JWT is often used together with OAuth 2.0 to transmit authentication information.
Main OAuth 2.0 flows:
- Authorization Code Flow — for server-side applications (most secure)
- Client Credentials Flow — for server-to-server communication
- Implicit Flow — deprecated, not recommended
- Resource Owner Password Flow — only if you trust the client
In this article, we will focus on the Client Credentials Flow, as it is the easiest to understand and is often used in microservices.
Setting up a Spring Boot Project in Kotlin
Let's create a new Spring Boot project with Kotlin support. Add the necessary dependencies to build.gradle.kts:
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") implementation("io.jsonwebtoken:jjwt-api:0.11.5") runtimeOnly("io.jsonwebtoken:jjwt-impl:0.11.5") runtimeOnly("io.jsonwebtoken:jjwt-jackson:0.11.5") implementation("com.fasterxml.jackson.module:jackson-module-kotlin")}These dependencies provide support for Spring Security, OAuth 2.0 Resource Server, and the JJWT library for working with JWT.
Creating JWT Tokens in Kotlin
Let's write a service for generating and validating JWT. This is the foundation of our authorization.
import io.jsonwebtoken.Jwtsimport io.jsonwebtoken.SignatureAlgorithmimport io.jsonwebtoken.security.Keysimport org.springframework.stereotype.Serviceimport java.util.Date
@Serviceclass JwtService { private val secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256) private val expirationMs = 3600000L // 1 hour
fun generateToken(clientId: String): String { val now = Date() val expiryDate = Date(now.time + expirationMs)
return Jwts.builder() .setSubject(clientId) .setIssuedAt(now) .setExpiration(expiryDate) .signWith(secretKey) .compact() }
fun validateToken(token: String): Boolean { return try { Jwts.parserBuilder() .setSigningKey(secretKey) .build() .parseClaimsJws(token) true } catch (e: Exception) { false } }
fun getClientIdFromToken(token: String): String { val claims = Jwts.parserBuilder() .setSigningKey(secretKey) .build() .parseClaimsJws(token) .body return claims.subject }}In this service, we use a symmetric key. In production, it is better to use asymmetric encryption (RS256) and