or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

basic-auth.mdbearer-auth.mdform-session-auth.mdindex.mdjvm-features.mdoauth.md
tile.json

tessl/maven-io-ktor--ktor-server-auth-jvm

Authentication and authorization plugin for Ktor server applications

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/io.ktor/ktor-server-auth-jvm@3.2.x

To install, run

npx @tessl/cli install tessl/maven-io-ktor--ktor-server-auth-jvm@3.2.0

index.mddocs/

Ktor Server Authentication

Comprehensive authentication and authorization capabilities for Ktor server applications. This module provides support for multiple authentication mechanisms including Basic, Bearer, Form-based, Session-based, Digest, OAuth 1.0a, and OAuth 2.0 authentication through a flexible provider-based architecture.

Package Information

  • Package Name: ktor-server-auth-jvm
  • Package Type: maven
  • Language: Kotlin
  • Installation:
    implementation("io.ktor:ktor-server-auth-jvm:3.2.0")

Core Imports

import io.ktor.server.auth.*
import io.ktor.server.application.*
import io.ktor.server.routing.*

Basic Usage

import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.routing.*
import io.ktor.server.response.*

fun Application.configureAuthentication() {
    install(Authentication) {
        basic("auth-basic") {
            realm = "Access to the '/' path"
            validate { credentials ->
                if (credentials.name == "admin" && credentials.password == "password") {
                    UserIdPrincipal(credentials.name)
                } else null
            }
        }
    }
    
    routing {
        authenticate("auth-basic") {
            get("/protected") {
                val principal = call.principal<UserIdPrincipal>()
                call.respond("Hello ${principal?.name}!")
            }
        }
    }
}

Architecture

The Ktor authentication module follows a provider-based architecture:

  • Authentication Plugin: Core plugin that manages multiple authentication providers
  • Authentication Providers: Specific implementations for different auth mechanisms (Basic, Bearer, OAuth, etc.)
  • Authentication Context: Manages authentication state and results during request processing
  • Principals: Represent authenticated users/identities
  • Credentials: Represent authentication data (username/password, tokens, etc.)
  • Challenge System: Handles authentication failures and response generation

Core Components

Authentication Plugin

Main plugin for handling authentication and authorization.

object Authentication : BaseApplicationPlugin<Application, AuthenticationConfig, Authentication>

fun Application.authentication(block: AuthenticationConfig.() -> Unit)

class AuthenticationConfig {
    fun provider(name: String?, configure: DynamicProviderConfig.() -> Unit)
    fun register(provider: AuthenticationProvider)
}

class DynamicProviderConfig(name: String?) {
    fun authenticate(block: (context: AuthenticationContext) -> Unit)
}

Authentication Context

val ApplicationCall.authentication: AuthenticationContext

inline fun <reified P : Any> ApplicationCall.principal(): P?
inline fun <reified P : Any> ApplicationCall.principal(provider: String?): P?

class AuthenticationContext {
    fun principal(principal: Any)
    fun principal(provider: String?, principal: Any)
    fun <T> principal(provider: String? = null): T?
    fun challenge(key: Any, cause: AuthenticationFailedCause, function: ChallengeFunction)
    fun error(key: Any, cause: AuthenticationFailedCause)
    val allErrors: List<AuthenticationFailedCause>
    val allFailures: List<AuthenticationFailedCause>
}

Route Protection

fun Route.authenticate(
    vararg configurations: String? = arrayOf(null),
    optional: Boolean = false,
    build: Route.() -> Unit
): Route

fun Route.authenticate(
    vararg configurations: String? = arrayOf(null),
    strategy: AuthenticationStrategy,
    build: Route.() -> Unit
): Route

enum class AuthenticationStrategy {
    Optional, FirstSuccessful, Required
}

class AuthenticationRouteSelector(val names: List<String?>)

object AuthenticationChecked

Capabilities

Basic Authentication

HTTP Basic authentication with username and password validation.

fun AuthenticationConfig.basic(
    name: String? = null,
    configure: BasicAuthenticationProvider.Config.() -> Unit
)

Basic Authentication

Bearer Token Authentication

Bearer token authentication for API access tokens and JWT tokens.

fun AuthenticationConfig.bearer(
    name: String? = null,
    configure: BearerAuthenticationProvider.Config.() -> Unit
)

Bearer Authentication

Form and Session Authentication

Form-based and session-based authentication for web applications.

fun AuthenticationConfig.form(
    name: String? = null,
    configure: FormAuthenticationProvider.Config.() -> Unit
)

fun <T : Any> AuthenticationConfig.session(
    name: String? = null,
    configure: SessionAuthenticationProvider.Config<T>.() -> Unit
)

Form and Session Authentication

OAuth Authentication

OAuth 1.0a and OAuth 2.0 support for third-party authentication providers.

fun AuthenticationConfig.oauth(
    name: String? = null,
    configure: OAuthAuthenticationProvider.Config.() -> Unit
)

OAuth Authentication

JVM-Specific Features

Digest authentication and comprehensive OAuth 1.0a support available only on JVM platform.

fun AuthenticationConfig.digest(
    name: String? = null,
    configure: DigestAuthenticationProvider.Config.() -> Unit
)

JVM-Specific Features

Common Types

Credentials

data class UserPasswordCredential(val name: String, val password: String)
data class BearerTokenCredential(val token: String)

Principals

data class UserIdPrincipal(val name: String)

Utility Classes

class UserHashedTableAuth(
    table: Map<String, ByteArray>,
    digester: (String) -> String
) {
    fun authenticate(credential: UserPasswordCredential): UserIdPrincipal?
}

Header Utilities

fun ApplicationRequest.parseAuthorizationHeader(): HttpAuthHeader?

Authentication Results

sealed class AuthenticationFailedCause {
    data object NoCredentials : AuthenticationFailedCause()
    data object InvalidCredentials : AuthenticationFailedCause()
    open class Error(val message: String) : AuthenticationFailedCause()
}

typealias ChallengeFunction = suspend PipelineContext<*, ApplicationCall>.(String, String) -> Unit
typealias AuthenticationFunction<C> = suspend ApplicationCall.(C) -> Any?
typealias ApplicationCallPredicate = (ApplicationCall) -> Boolean

Response Types

class UnauthorizedResponse(
    challenge: HttpAuthHeader = HttpAuthHeader.basicAuthChallenge("Ktor Server")
) : HttpStatusCodeContent

class ForbiddenResponse(message: String = "Forbidden") : HttpStatusCodeContent

Platform Availability

  • Common: Basic, Bearer, Form, Session authentication, OAuth 2.0
  • JVM Only: Digest authentication, OAuth 1.0a
  • JS/WASM/Native: Limited OAuth support through platform-specific implementations