I read this article and I rewrite it in my own words.
A guide to implementing delegated authorization and stateless authentication in modern backend services.
The Shift Toward Defensive API Design
API security stopped being a bolt-on feature the moment microservices became the default architecture. When a single user request triggers a cascade of calls across five different services, traditional session-based authentication collapses under the weight of database lookups and state synchronization. Kotlin has emerged as a preferred language for building these backends, largely because its type system and coroutine support allow for expressive, safe security configurations.
Modern security relies on two primary pillars: OAuth2 for authorization and JSON Web Tokens (JWT) for authentication. While beginners often conflate the two, they serve distinct purposes. OAuth2 defines how a user grants a third-party application access to their data without handing over their password. JWT provides the mechanism for encoding that access into a portable, verifiable format. Organizations like JetBrains emphasize that securing APIs for beginners requires moving away from local JSESSIONID cookies toward token-based flows that work across mobile apps, web frontends, and server-to-server communication.
In the Kotlin ecosystem, the choice often lands between Spring Security and Ktor. Spring Security provides a mature, albeit complex, framework for enterprise-grade protection, while Ktor offers a lightweight, DSL-driven approach. Regardless of the framework, the goal remains the same: ensure that every incoming request is authenticated (identifying who the user is) and authorized (verifying what they are allowed to do) without introducing a single point of failure or an unnecessary performance bottleneck.
OAuth2: The Delegated Authorization Framework
OAuth2 is not an authentication protocol; it is an authorization framework. It solves the "password sharing" problem by introducing an intermediary—the Authorization Server. In a typical Kotlin backend, the application assumes the role of a Resource Server, protecting data on behalf of the user.
According to the OAuth 2.0 Authorization Framework (RFC 6749), the system relies on four distinct roles working in concert:
┌──────────────┐ ┌──────────────────────┐
│ Resource │ (A) │ │
│ Owner (User) │ ────────▶│ Client App │
└──────────────┘ │ (Mobile/Web/Server) │
▲ └──────────────────────┘
│ │
│ (B) Grant │ (C) Access Token
▼ ▼
┌──────────────┐ ┌──────────────────────┐
│ Authorization│ │ Resource Server │
│ Server │ │ (Kotlin API) │
└──────────────┘ └──────────────────────┘
For most Kotlin developers, the Authorization Code Flow is the standard. The client redirects the user to an identity provider (like Keycloak, Auth0, or Google). After the user logs in, the provider sends a temporary code back to the client. The client then exchanges this code for an access_token. Spring Security's OAuth2 support automates much of this handshake, allowing developers to focus on defining protected endpoints rather than managing the low-level HTTP redirects.
By delegating the login process to a specialized server, you reduce the attack surface of your own application. You don't store passwords, manage password resets, or handle multi-factor authentication (MFA) logic. You simply trust the tokens issued by the Authorization Server, provided they meet your validation criteria.
Anatomy of a JSON Web Token
If OAuth2 is the process, the JSON Web Token (JWT) is the artifact. A JWT is a compact, URL-safe string representing claims to be transferred between two parties. Its primary advantage is that it is self-contained. All the necessary user data—their ID, roles, and the token expiration—is encoded directly in the string.
A JWT consists of three parts separated by dots: the Header, the Payload, and the Signature.
-
Header: Specifies the algorithm used for signing (e.g.,
HS256orRS256). -
Payload: Contains the "claims." These are statements about the user and additional data like
iat(issued at) andexp(expiration time). - Signature: Created by hashing the header and payload with a secret key. This ensures the token hasn't been tampered with.
Ktor's JWT implementation allows you to verify these signatures using either a shared secret or a public/private key pair. In a production environment, RS256 (Asymmetric) is preferred. The Authorization Server signs the token with a private key, and your Kotlin API verifies it using a public key.
// Example of a JWT payload structure
{
"sub": "1234567890",
"name": "Jane Doe",
"admin": true,
"iat": 1516239022,
"exp": 1516242622
}
Because the token is signed, the Resource Server can trust the admin: true claim without querying a database on every request. This enables stateless authentication, where the server doesn't need to store session data in memory or a cache like Redis. However, this carries a trade-off: tokens are difficult to revoke before they expire. If a token is stolen, the attacker has access until the exp timestamp is reached. This makes short-lived tokens and refresh token patterns mandatory for any secure implementation.
Implementing Security in the Kotlin Ecosystem
When moving from theory to code, Kotlin developers generally choose between the Spring Boot ecosystem and the Ktor framework. Each offers distinct patterns for integrating OAuth2 and JWT.
Spring Boot and Spring Security
Spring Boot provides extensive auto-configuration. By adding the spring-boot-starter-oauth2-resource-server dependency, you can configure your application to validate JWTs by simply pointing to an issuer URI. Baeldung’s guide on Spring Security OAuth JWT notes that you can even include custom claims in the token to pass domain-specific data, such as a subscription tier or a tenant ID.
@Configuration
@EnableWebSecurity
class SecurityConfig {
@Bean
fun filterChain(http: HttpSecurity): SecurityFilterChain {
http
.authorizeHttpRequests { auth ->
auth.requestMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
}
.oauth2ResourceServer { oauth2 ->
oauth2.jwt { jwt ->
// Configure JWT validation here
}
}
return http.build()
}
}
Ktor Server
Ktor takes a more explicit approach using its Authentication plugin. As detailed in the Ktor Authentication documentation, you install the JWT provider and define how to validate the credentials. This is often more idiomatic for Kotlin developers who prefer a functional style over Spring's annotation-heavy architecture.
install(Authentication) {
jwt("auth-jwt") {
realm = "my-api"
verifier(makeJwtVerifier(issuer, audience))
validate { credential ->
if (credential.payload.getClaim("username").asString() != "") {
JWTPrincipal(credential.payload)
} else {
null
}
}
}
}
For teams that want to avoid the overhead of a dedicated Authorization Server like Keycloak, it is possible to implement stateless JWT authentication manually, where the API itself issues and validates tokens. This is often suitable for smaller projects where vendor lock-in or the cost of SaaS identity providers is a concern.
Security Best Practices and Common Pitfalls
Implementing the protocols is only half the battle; configuring them securely is where most vulnerabilities arise. One of the most frequent mistakes is using weak signing keys. For HS256, the secret should be a high-entropy string of at least 256 bits. For RS256, generating a proper Java KeyStore (JKS) ensures that your private keys are stored securely and not hardcoded in application properties.
Token Expiration and Refreshing
Never issue access tokens with long lifespans. A standard practice is 15 minutes for an access token, paired with a longer-lived refresh token stored in an HttpOnly, Secure cookie. This limits the window of opportunity for an attacker if a token is intercepted. Software Patterns Lexicon highlights that token validation must include checks for the nbf (not before) and iat (issued at) claims to prevent replay attacks.
Algorithm Verification
A classic JWT vulnerability involves the "alg": "none" attack, where an attacker modifies the header to disable signature verification. Modern libraries like java-jwt or Spring Security's NimbusJwtDecoder protect against this by default, but you must explicitly define the expected algorithm during the verification phase.
Scope vs. Role
In OAuth2, scopes represent what the application is allowed to do (e.g., read:profile), while roles represent what the user is allowed to do (e.g., ROLE_ADMIN). Mixing these up leads to over-privileged applications. Always validate both the presence of the correct scope and the user's roles before granting access to sensitive data.
Finally, monitor your logs for frequent 401 Unauthorized or 403 Forbidden errors. While these are often benign user errors, a sudden spike can indicate a brute-force attempt or a misconfigured client attempting to use an expired refresh token. Security is a moving target, and in the Kotlin ecosystem, staying updated with the latest Ktor OAuth features or Spring Boot releases is the best defense against emerging threats.
References
- Secure Your APIs: OAuth2 and JWT for Beginners — The primary source context providing the motivation for the article.
- The OAuth 2.0 Authorization Framework — The definitive specification for OAuth2 roles and flows.
- OAuth2 :: Spring Security — Official documentation for integrating OAuth2 into Spring-based Kotlin applications.
- JSON Web Tokens | Ktor Documentation — Reference for handling JWT authentication within the Ktor framework.
- Using JWT with Spring Security OAuth | Baeldung — Technical guide covering custom claims and keystore management.
- Authentication and authorization in Ktor Server — Overview of the Ktor Authentication plugin and its supported schemes.
- Stateless JWT Authentication with Spring Security — Explores implementing JWT without a dedicated authorization server.
- OAuth2 and JWT in Kotlin: Secure Authentication and Token Management — Discusses design patterns for token validation and refresh mechanisms.
- OAuth | Ktor Documentation — Details on configuring external OAuth providers in Ktor.
Top comments (0)