CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-io-ktor--ktor-client-auth

Ktor client authentication and authorization plugin that handles various authentication schemes including Basic, Bearer, and Digest authentication.

Pending
Overview
Eval results
Files

auth-plugin.mddocs/

Auth Plugin

Core authentication plugin for Ktor HTTP clients that manages authentication providers and handles the authentication flow automatically.

Capabilities

Auth Plugin Installation

Install the Auth plugin with configuration for authentication providers and unauthorized response detection.

/**
 * Install Auth plugin with configuration
 * @param block Configuration block for AuthConfig
 */
fun HttpClientConfig<*>.Auth(block: AuthConfig.() -> Unit)

/**
 * Core authentication plugin instance
 */
val Auth: ClientPlugin<AuthConfig>

Usage Example:

import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.auth.*
import io.ktor.client.plugins.auth.providers.*

val client = HttpClient(CIO) {
    install(Auth) {
        // Configure authentication providers
        bearer { /* bearer config */ }
        basic { /* basic config */ }
        
        // Optional: customize unauthorized response detection
        reAuthorizeOnResponse { response ->
            response.status == HttpStatusCode.Unauthorized || 
            response.status == HttpStatusCode.Forbidden
        }
    }
}

AuthConfig Class

Configuration class for the Auth plugin containing provider management and response detection.

/**
 * Configuration for Auth plugin
 */
class AuthConfig {
    /**
     * List of authentication providers to use
     */
    val providers: MutableList<AuthProvider>
    
    /**
     * Set custom function to detect unauthorized responses
     * @param block Function that returns true if response should trigger re-auth
     */
    fun reAuthorizeOnResponse(block: suspend (HttpResponse) -> Boolean)
}

The default unauthorized response detector checks for HTTP 401 status code:

// Default implementation
isUnauthorizedResponse = { it.status == HttpStatusCode.Unauthorized }

Circuit Breaker

Attribute key used to prevent infinite authentication loops by marking requests that should skip authentication.

/**
 * Attribute key to mark requests that should skip auth procedures
 */
val AuthCircuitBreaker: AttributeKey<Unit>

Usage Example:

// Mark a request to skip authentication (e.g., token refresh request)
val request = HttpRequestBuilder().apply {
    attributes.put(AuthCircuitBreaker, Unit)
}

HttpClient Extensions

Extension functions for accessing configured authentication providers.

/**
 * Get list of all configured authentication providers
 */
val HttpClient.authProviders: List<AuthProvider>

/**
 * Get specific authentication provider by type
 * @return Provider instance or null if not found
 */
inline fun <reified T : AuthProvider> HttpClient.authProvider(): T?

Usage Examples:

// Get all providers
val allProviders = client.authProviders

// Get specific provider type
val bearerProvider = client.authProvider<BearerAuthProvider>()
bearerProvider?.clearToken() // Clear cached tokens if needed

// Check if Basic auth is configured
val hasBasicAuth = client.authProvider<BasicAuthProvider>() != null

Authentication Flow

The Auth plugin follows this automatic flow:

  1. Request Interception: Providers that send without waiting for 401 add headers preemptively
  2. Response Analysis: If response is unauthorized, find applicable provider based on WWW-Authenticate header
  3. Token Refresh: Attempt to refresh tokens if provider supports it
  4. Retry Request: Add authentication headers and retry the request
  5. Circuit Breaking: Prevent infinite loops by tracking request attributes

Error Handling

The Auth plugin handles various error scenarios:

  • No WWW-Authenticate Header: Logs warning and uses single provider if available
  • No Applicable Provider: Returns original response without retry
  • Refresh Failure: Returns original response if token refresh fails
  • Infinite Loops: Circuit breaker prevents repeated authentication attempts

Install with Tessl CLI

npx tessl i tessl/maven-io-ktor--ktor-client-auth

docs

auth-plugin.md

basic-auth.md

bearer-auth.md

digest-auth.md

index.md

tile.json