OAuth
suggest changeOAuth 2.0 is the industry-standard protocol for authorization, allowing applications to securely obtain delegated access to server resources on behalf of a user or system. OpenID Connect (OIDC) layers identity verification on top of OAuth 2.0 using JSON Web Tokens (JWT).
In Kotlin, OAuth workflows are commonly implemented using Ktor's authentication plugins, Spring Security, or standalone HTTP clients like Ktor Client or OkHttp.
Core Roles and Flows
- Authorization Code Grant with PKCE: Standard flow for web applications and mobile apps where users log in via an external Identity Provider (e.g., Google, GitHub, Auth0, Keycloak).
- Client Credentials Grant: Machine-to-machine (M2M) flow where a backend service authenticates directly using a client ID and secret without user involvement.
OAuth 2.0 Web Authentication with Ktor Server
Ktor Server provides an oauth authentication provider that manages authorization redirects, callback validation, and code-for-token exchanges.
Configuration
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.sessions.*
// Session to persist user authentication
data class UserSession(val token: String, val userId: String)
fun Application.configureOAuth() {
install(Sessions) {
cookie<UserSession>("USER_SESSION") {
cookie.path = "/"
cookie.maxAgeInSeconds = 3600
cookie.secure = true
cookie.httpOnly = true
}
}
val httpClient = HttpClient(CIO)
install(Authentication) {
oauth("auth-oauth-google") {
urlProvider = { "https://myapp.example.com/callback" }
providerLookup = {
OAuthServerSettings.OAuth2ServerSettings(
name = "google",
authorizeUrl = "https://accounts.google.com/o/oauth2/v2/auth",
accessTokenUrl = "https://oauth2.googleapis.com/token",
requestMethod = HttpMethod.Post,
clientId = System.getenv("GOOGLE_CLIENT_ID") ?: "",
clientSecret = System.getenv("GOOGLE_CLIENT_SECRET") ?: "",
defaultScopes = listOf("https://www.googleapis.com/auth/userinfo.profile", "email")
)
}
client = httpClient
}
}
routing {
authenticate("auth-oauth-google") {
// Initiates redirection to Google OAuth consent page
get("/login") {}
// Identity provider redirects back here with code and state
get("/callback") {
val principal: OAuthAccessTokenResponse.OAuth2? = call.principal()
if (principal != null) {
val accessToken = principal.accessToken
val refreshToken = principal.refreshToken
// Store access token in session cookie
call.sessions.set(UserSession(token = accessToken, userId = "user_oauth"))
call.respondRedirect("/dashboard")
} else {
call.respond(HttpStatusCode.Unauthorized, "OAuth authorization failed.")
}
}
}
get("/dashboard") {
val session = call.sessions.get<UserSession>()
if (session == null) {
call.respondRedirect("/login")
} else {
call.respondText("Welcome to your dashboard! Session token: ${session.token.take(10)}...")
}
}
}
}
Machine-to-Machine Client Credentials Flow
For backend-to-backend communication, services obtain an access token using their own credentials:
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.forms.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import java.time.Instant
@Serializable
data class TokenResponse(
@SerialName("access_token") val accessToken: String,
@SerialName("token_type") val tokenType: String,
@SerialName("expires_in") val expiresIn: Long
)
class OAuthClientCredentialsService(
private val tokenUrl: String,
private val clientId: String,
private val clientSecret: String
) {
private val client = HttpClient(CIO) {
install(ContentNegotiation) {
json(Json { ignoreUnknownKeys = true })
}
}
private var cachedToken: String? = null
private var tokenExpiry: Instant = Instant.MIN
suspend fun getValidAccessToken(): String {
// Return cached token if valid with 30s buffer
if (cachedToken != null && Instant.now().isBefore(tokenExpiry.minusSeconds(30))) {
return cachedToken!!
}
val response: TokenResponse = client.submitForm(
url = tokenUrl,
formParameters = parameters {
append("grant_type", "client_credentials")
append("client_id", clientId)
append("client_secret", clientSecret)
}
).body()
cachedToken = response.accessToken
tokenExpiry = Instant.now().plusSeconds(response.expiresIn)
return response.accessToken
}
}
Securing Resource Endpoints with JWT Verification
Resource servers validate incoming OAuth bearer tokens before granting access. In Ktor, use the jwt authentication provider to verify signatures against the authorization server's JWKS (JSON Web Key Set):
import com.auth0.jwk.JwkProviderBuilder
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import java.net.URI
import java.util.concurrent.TimeUnit
fun Application.configureJwtResourceServer() {
val issuer = "https://identity.example.com/"
val audience = "https://api.example.com"
val jwkProvider = JwkProviderBuilder(URI(issuer).toURL())
.cached(10, 24, TimeUnit.HOURS)
.rateLimited(10, 1, TimeUnit.MINUTES)
.build()
install(Authentication) {
jwt("auth-jwt") {
realm = "Access to protected API"
verifier(jwkProvider, issuer) {
acceptLeeway(3)
withAudience(audience)
}
validate { credential ->
if (credential.payload.audience.contains(audience)) {
JWTPrincipal(credential.payload)
} else null
}
}
}
routing {
authenticate("auth-jwt") {
get("/api/orders") {
val principal = call.principal<JWTPrincipal>()
val subject = principal?.payload?.subject
call.respondText("Orders for user: $subject")
}
}
}
}
Security Best Practices
- Always Use PKCE (Proof Key for Code Exchange): PKCE prevents authorization code injection attacks and is essential for public and native clients.
- Strict
stateParameter Validation: Always generate and verify a cryptographically secure randomstatestring to guard against CSRF attacks in the authorization flow. - Never Expose Client Secrets: Keep client secrets restricted to secure backend environments. Never embed secrets in Android or multiplatform client apps.
- Cache and Proactively Refresh Tokens: Refresh access tokens before they expire to prevent unexpected request failures across asynchronous coroutine pipelines.