Introduction to OAuth 2.0 and JWT in Kotlin
Modern web applications and mobile services require a reliable and secure 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 thoroughly examine how to implement OAuth 2.0 and JWT authorization in Kotlin using the Spring Boot framework. You will learn how to configure an authorization server, generate and verify tokens, and protect your API endpoints.
Basics of OAuth 2.0 and JWT
What is OAuth 2.0?
OAuth 2.0 is an authorization protocol that allows third-party applications to obtain limited access to a user's resources without transmitting their credentials (login and password). Instead, an access token is used, which is issued after successful authentication. The main participants of OAuth 2.0 are:
- Resource Owner — the user.
- Client — the application requesting access.
- Authorization Server — the server that issues tokens.
- Resource Server — the server that provides protected data.
What is JWT?
JWT (JSON Web Token) is a compact and self-contained token format that contains information about the user (claims) in the form of a JSON object. The token is signed using a secret key or asymmetric encryption, which guarantees its integrity. The JWT structure consists of three parts separated by dots:
- Header — contains the token type and signing algorithm.
- Payload — the payload with data (e.g., userId, role, exp).
- Signature — a signature created based on the header and payload.
Example of a JWT: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIn0.ZL1mK9WpXoQ
Setting up a Kotlin Project with Spring Security
Adding Dependencies
First, let's create a new Spring Boot project in Kotlin. Add the following dependencies to the build.gradle.kts file:
dependencies { implementation("org.springframework.boot:spring-boot-starter-web") implementation("org.springframework.boot:spring-boot-starter-security") implementation("org.springframework.boot:spring-boot-starter-data-jpa") 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.h2database:h2")}We are using the jjwt library for working with JWT and H2 as a database for testing.
Security Configuration
Let's create a SecurityConfig class that will configure Spring Security and disable the default login form:
@Configuration@EnableWebSecurityclass SecurityConfig(private val jwtAuthFilter: JwtAuthFilter) {
@Bean fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http .csrf { it.disable() } .authorizeHttpRequests { auth -> auth.requestMatchers("/api/auth/**").permitAll() .anyRequest().authenticated() } .sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) } .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter::class.java) return http.build() }}We allow access to the /api/auth/** endpoints without authentication, while all other requests require a JWT token.
Implementing OAuth 2.0 and JWT in Kotlin
Generating and Verifying JWT Tokens
Let's create a JwtService service that will be responsible for creating and