Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 38 ยท Authentication

OAuth and Authorization

Add Sign in with an identity provider using Ktor's OAuth provider, understand the authorization code flow with state and PKCE, and enforce roles with a route-scoped plugin.

This lesson closes the authentication chapter with two topics that finish the picture. First, OAuth 2.0: letting users sign in with an existing account (Google, GitHub and others) so you never handle their password. Second, authorization: after you know who the caller is, deciding what they may do, with roles and ownership checks. Both are shown with real Ktor code (read-only, because the runner has no Ktor and no network) and runnable stand-ins that implement the underlying mechanics.

The OAuth 2.0 authorization code flow

OAuth lets your application obtain limited access on a user's behalf from another service, or learn who the user is (OpenID Connect adds a standard identity layer on top). The flow your server uses is the authorization code flow:

sequenceDiagram
    participant U as Browser
    participant A as Your Ktor app
    participant P as Identity provider
    U->>A: GET /login
    A->>U: 302 to provider /authorize (client_id, redirect_uri, state, scope)
    U->>P: user logs in and approves
    P->>U: 302 to your /callback?code=...&state=...
    U->>A: GET /callback?code=...&state=...
    A->>P: POST /token (code, client_secret) server to server
    P->>A: access_token (and id_token)
    A->>U: create session, redirect to /dashboard

The user's password only ever goes to the provider. Your app receives a short-lived code, exchanges it server to server for tokens, and then creates its own session.

The security-critical parts:

  • state: a random value your app generates before redirecting and checks when the browser returns. It ties the callback to the browser that started the flow and defeats login CSRF.
  • redirect_uri: must exactly match one registered with the provider, so codes only go to your server.
  • client_secret: known only to your server and used in the back-channel token request.
  • PKCE (Proof Key for Code Exchange): the app creates a random code_verifier, sends its SHA-256 hash (code_challenge) in the first redirect, and proves possession of the verifier when exchanging the code. It protects the code from interception and is required for public clients (mobile apps, SPAs) and recommended for all.

Ktor's OAuth provider

Dependencies: ktor-server-auth and a Ktor HttpClient (for the token request), e.g. ktor-client-cio.

Kotlin
val httpClient = HttpClient(CIO) { install(ClientContentNegotiation) { json() } }

install(Authentication) {
    oauth("auth-oauth-github") {
        urlProvider = { "http://localhost:8080/callback" }
        providerLookup = {
            OAuthServerSettings.OAuth2ServerSettings(
                name = "github",
                authorizeUrl = "https://github.com/login/oauth/authorize",
                accessTokenUrl = "https://github.com/login/oauth/access_token",
                requestMethod = HttpMethod.Post,
                clientId = System.getenv("GITHUB_CLIENT_ID"),
                clientSecret = System.getenv("GITHUB_CLIENT_SECRET"),
                defaultScopes = listOf("read:user"),
                onStateCreated = { call, state -> /* remember state, e.g. in the session */ }
            )
        }
        client = httpClient
    }
}

routing {
    authenticate("auth-oauth-github") {
        get("/login") { /* Ktor redirects to the provider automatically */ }
        get("/callback") {
            val principal: OAuthAccessTokenResponse.OAuth2? = call.principal()
            val accessToken = principal?.accessToken
                ?: return@get call.respond(HttpStatusCode.Unauthorized)
            val profile = httpClient.get("https://api.github.com/user") {
                bearerAuth(accessToken)
            }.body<GitHubUser>()
            call.sessions.set(UserSession(profile.login, System.currentTimeMillis()))
            call.respondRedirect("/dashboard")
        }
    }
}

authenticate on /login makes Ktor perform the redirect; on /callback it validates state, exchanges the code and gives you the principal with the access token. You then fetch the user's profile, create your own session (see Sessions and Cookies) and carry on. Register your application with the provider to get a client ID and secret, and keep both in environment variables.

Stand-in: authorization code flow with state and PKCE

The program below simulates a provider and an app in memory, using the JDK's real SHA-256 and Base64URL for PKCE. It runs four scenarios: a good login, a callback with a wrong state (CSRF), a code replayed twice, and a code exchange with the wrong PKCE verifier. Randomness is seeded, so the output is stable.

Kotlin Stand-in: OAuth code flow with state and PKCE

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Case 4 is the value of PKCE: even with the code in hand, the attacker cannot complete the exchange without the original verifier.

Authorization: what may this user do?

Authentication yields a principal; authorization compares it with the action. Three levels, from coarse to fine:

  1. Authenticated or not: authenticate { }.
  2. Role based (RBAC): admin can delete users, editor can edit articles, reader can read.
  3. Resource based (ownership): you may edit this article only if you wrote it. Roles alone cannot express this; check in the handler or service.

Ktor has no built-in role plugin, but route-scoped plugins make a clean one. The AuthenticationChecked hook runs after authentication, so the principal is available:

Kotlin
class RoleConfig { var roles: Set<String> = emptySet() }

val RoleAuthorization = createRouteScopedPlugin("RoleAuthorization", ::RoleConfig) {
    on(AuthenticationChecked) { call ->
        val principal = call.principal<JWTPrincipal>() ?: return@on   // authentication plugin handles 401
        val role = principal.payload.getClaim("role").asString()
        if (role !in pluginConfig.roles) {
            call.respond(HttpStatusCode.Forbidden, "Requires one of ${pluginConfig.roles}")
        }
    }
}

fun Route.withRoles(vararg roles: String, build: Route.() -> Unit): Route {
    val route = createChild(object : RouteSelector() {
        override suspend fun evaluate(context: RoutingResolveContext, segmentIndex: Int) =
            RouteSelectorEvaluation.Constant
        override fun toString() = "(roles ${roles.toList()})"
    })
    route.install(RoleAuthorization) { this.roles = roles.toSet() }
    route.build()
    return route
}

routing {
    authenticate("auth-jwt") {
        get("/articles") { /* any logged-in user */ }
        withRoles("admin") {
            delete("/users/{id}") { /* admins only */ }
        }
    }
}

Return 401 when nobody is authenticated and 403 when the user is known but lacks permission, as in the status codes lesson. Ownership checks go in the handler:

Kotlin
put("/articles/{id}") {
    val principal = call.principal<JWTPrincipal>()!!
    val article = repo.find(call.parameters.getOrFail<Int>("id")) ?: throw NotFound("Article")
    if (article.authorId != principal.subject && role != "admin") throw Forbidden()
    // ...
}

Stand-in: role and ownership checks

This stand-in implements the decision logic: a can(user, action, resource) policy function, with roles mapping to permissions and an ownership rule, evaluated for a list of requests, and answering 401, 403, 404 or 200 as an API should.

Kotlin Stand-in: roles, ownership and 401 vs 403

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Apply the principle of least privilege: new users get the lowest role, deny by default, and test the "no" paths (401, 403) as carefully as the "yes" paths.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the purpose of the OAuth state parameter?

    The app generates a random state, and rejects a callback whose state does not match.
  2. 2. In the authorization code flow, who sees the user's password?

    The user logs in at the provider; your app receives only a code and tokens.
  3. 3. A logged-in reader tries to delete a user. What should the API return?

    The caller is authenticated but not permitted, so 403.
  4. 4. What problem does PKCE solve?

    The token exchange requires the verifier whose hash was sent in the first request.
  5. 5. Why are role checks alone not enough for 'edit my own article'?

    Resource-level rules need the resource; roles describe only the kind of user.

Summary

  • OAuth 2.0's authorization code flow keeps passwords with the identity provider; validate state, register exact redirect URIs, and use PKCE.
  • Ktor's oauth provider performs the redirect and token exchange; you then create your own session or token.
  • Authorization is separate from authentication: use roles (RBAC) for kinds of users and ownership checks for specific resources.
  • Respond 401 for unknown callers, 403 for known but forbidden ones, and deny by default.

You can now identify users and restrict what they can do. The next chapter stores their data with Exposed.

Next: Exposed Basics - Tables, Transactions and CRUD