OAuth 2.0 and JWT Authorization in Kotlin: A Complete Guide for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What are OAuth 2.0 and JWT and why are they needed in Kotlin?

\n\n

In modern web development, data security and access management are among the key tasks. If you are writing a server application in Kotlin, sooner or later you will face the need to protect an API or organize login through third-party services (Google, GitHub, VK). For this, there are two standards — OAuth 2.0 (authorization protocol) and JWT (JSON Web Token — token format).

\n\n

In this article, we will break down how OAuth 2.0 and JWT work, and implement simple authorization in Kotlin using popular libraries. The material is designed for beginners, so all complex terms will be explained in simple language.

\n\n

Basic Concepts: OAuth 2.0 and JWT

\n\n

What is OAuth 2.0?

\n

OAuth 2.0 is a protocol that allows one service (e.g., your application) to obtain limited access to a user's resources on another service (e.g., their Google profile) without transmitting their login and password. Imagine you want to log into a website using your Google account — that is OAuth 2.0.

\n\n

The main participants of OAuth 2.0:

\n
    \n
  • Resource Owner — the user, the data owner.
  • \n
  • Client — your application that wants to gain access.
  • \n
  • Authorization Server — the server that issues permission (e.g., Google).
  • \n
  • Resource Server — the server storing the user's data (e.g., Google API).
  • \n
\n\n

What is JWT?

\n

JWT is a compact and self-contained token format that contains information about the user (e.g., ID, role, expiration date). The token is signed with a digital signature, so it cannot be forged. JWT consists of three parts separated by dots:

\n\n
header.payload.signature
\n\n

Example of a decoded JWT:

\n
{\n  "sub": "1234567890",\n  "name": "Ivan Petrov",\n  "iat": 1516239022,\n  "exp": 1516242622\n}
\n\n

The main advantage of JWT is that the server does not need to store sessions in the database. All the information is already inside the token.

\n\n

Implementing JWT Authorization in Kotlin with Spring Boot

\n\n

Let's look at a practical example. We will create a REST API in Kotlin using Spring Boot and Spring Security. Our application will issue a JWT token upon successful authentication.

\n\n

Step 1. Adding Dependencies

\n

Add the following dependencies to build.gradle.kts:

\n\n
dependencies {\n    implementation("org.springframework.boot:spring-boot-starter-security")\n    implementation("org.springframework.boot:spring-boot-starter-web")\n    implementation("io.jsonwebtoken:jjwt-api:0.12.5")\n    runtimeOnly("io.jsonwebtoken:jjwt-impl:0.12.5")\n    runtimeOnly("io.jsonwebtoken:jjwt-jackson:0.12.5")\n}
\n\n

Step 2. Creating the JWT Service

\n

Let's create a JwtService class that will generate and validate tokens:

\n\n
import io.jsonwebtoken.Claims\nimport io.jsonwebtoken.Jwts\nimport io.jsonwebtoken.security.Keys\nimport org.springframework.stereotype.Service\nimport java.util.*\n\n@Service\nclass JwtService {\n    private val secretKey = "mySecretKeyForJwtToken12345678901234567890" // minimum 32 characters\n    private val expirationMs = 3600000L // 1 hour\n\n    fun generateToken(username: String): String {\n        val claims: Map = mapOf(\n            "sub" to username,\n            "iat" to Date(),\n            "exp" to Date(System.currentTimeMillis() + expirationMs)\n        )\n        return Jwts.builder()\n            .claims(claims)\n            .signWith(Keys.hmacShaKeyFor(secretKey.toByteArray()))\n            .compact()\n    }\n\n    fun extractUsername(token: String): String? {\n        return try {\n            val claims = parseToken(token)\n            claims.subject\n        } catch (e: Exception) {\n            nul                

Blogs

Book Recommendations