Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 38 ยท Authentication

Authentication Basics

Protect Ktor routes: the Authentication plugin, named providers, HTTP Basic auth, call.principal, 401 challenges, and storing passwords safely with salted hashes.

Authentication answers one question: who is making this request? (Authorization, which you will meet in the last lesson of this chapter, answers what are they allowed to do?) In Ktor, authentication is a plugin with a set of pluggable providers: Basic, Bearer, JWT, sessions, OAuth, forms and more. You configure providers by name, then wrap routes in authenticate("name") { ... }. This lesson teaches that structure with the simplest provider, HTTP Basic, and then covers the most important companion topic: how to store passwords.

How Ktor authentication is structured

flowchart LR
    A["Request"] --> B["Authentication plugin"]
    B --> C{"Provider validates<br/>credentials"}
    C -- "Principal" --> D["authenticate block:<br/>handler runs"]
    C -- "null" --> E["Challenge: 401"]

A provider extracts credentials from the request and returns a principal (an object describing the user) or null. Routes inside authenticate run only when a principal exists.

Three terms:

  • Credential: what the client sent (username and password, a token).
  • Principal: your server's identity object after successful validation, for example UserIdPrincipal("ann").
  • Challenge: the response sent when authentication fails, typically 401 Unauthorized with a WWW-Authenticate header.

HTTP Basic authentication

Basic auth sends Authorization: Basic base64(username:password) with every request. It is simple and fine for internal tools, scripts and as a learning step. It must be used only over HTTPS, because base64 is encoding, not encryption.

Dependency: ktor-server-auth.

Kotlin
import io.ktor.server.auth.*

fun Application.module() {
    install(Authentication) {
        basic("auth-basic") {
            realm = "Access to the '/' path"
            validate { credentials ->
                val user = userService.verify(credentials.name, credentials.password)
                if (user != null) UserIdPrincipal(credentials.name) else null
            }
        }
    }
    routing {
        get("/") { call.respondText("Public page") }

        authenticate("auth-basic") {
            get("/profile") {
                val principal = call.principal<UserIdPrincipal>()!!
                call.respondText("Hello, ${principal.name}")
            }
            get("/settings") { call.respondText("Your settings") }
        }
    }
}

What happens:

  1. The provider is registered under the name "auth-basic".
  2. Its validate lambda receives UserPasswordCredential (name and password) and returns a principal or null.
  3. Everything inside authenticate("auth-basic") { } needs a valid principal. Without or with wrong credentials Ktor sends 401 and WWW-Authenticate: Basic realm="...", which makes a browser show a login dialog.
  4. Inside, call.principal<UserIdPrincipal>() returns the identity (non-null inside the block).

You can define several providers and even require "any of" them: authenticate("auth-basic", "auth-jwt") { ... } accepts either. authenticate("name", optional = true) { } lets anonymous users through but still fills in the principal when credentials are present, which is useful for pages that look different for logged-in users.

Passwords: never store them in plain text

If your database leaks, plain-text passwords expose users on every other site where they reused them. The rule: store only a salted, slow hash.

  • Salt: random bytes unique per user, stored beside the hash, so two users with the same password have different hashes and precomputed tables are useless.
  • Slow: the hash function must be deliberately expensive. Use bcrypt, scrypt, Argon2id or PBKDF2 with a high iteration count. Plain SHA-256 is far too fast.
  • Constant-time comparison when checking, so response timing reveals nothing.

Libraries make this easy (at.favre.lib:bcrypt, or Argon2 bindings). The JDK itself ships PBKDF2, which the stand-in uses.

Stand-in: Basic auth and PBKDF2, end to end

The program below implements the whole flow with a real HTTP server on loopback and the JDK's real crypto: password hashing with salt and PBKDF2, a basic provider that returns a principal or null, a protected /profile, and a client that tries no credentials, wrong credentials and right credentials.

Kotlin Stand-in: Basic auth with salted PBKDF2 hashes

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.

Observe: the public page needs nothing; /profile answers 401 with a WWW-Authenticate challenge for missing, wrong and unknown credentials, and the response is identical for "unknown user" and "wrong password", so attackers cannot discover which usernames exist.

Other providers at a glance

Provider Credentials from Typical use
basic Authorization: Basic ... Internal tools, simple APIs over HTTPS
form A posted login form Server-rendered sites
bearer Authorization: Bearer <token> Opaque API tokens you look up yourself
jwt A signed JWT Stateless APIs (next lesson)
session A cookie session Browser apps (sessions)
oauth An external identity provider "Sign in with Google/GitHub"

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a principal in Ktor authentication?

    A provider returns a principal (like UserIdPrincipal) on success, or null.
  2. 2. What does the server send when credentials are missing in an authenticate block with Basic auth?

    The challenge is 401 plus WWW-Authenticate, which prompts browsers to ask for credentials.
  3. 3. Which is the right way to store user passwords?

    Salted, deliberately slow hashes make stolen databases hard to crack.
  4. 4. Why should Basic auth be used only over HTTPS?

    Without TLS anyone on the path can read the credentials.

Summary

  • Install Authentication, register named providers, and wrap routes in authenticate("name") { }.
  • A provider turns credentials into a principal or null; failure yields a 401 challenge.
  • call.principal<T>() returns the identity inside protected routes.
  • Store only salted, slow password hashes, compare in constant time, and give identical errors for unknown users and wrong passwords.
  • Use Basic only over HTTPS; other providers cover tokens, sessions and OAuth.

Next: Bearer Tokens and JWT