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

basic-auth.mddocs/

Basic Authentication

Username/password authentication using HTTP Basic authentication scheme. Suitable for simple authentication scenarios and internal APIs with credential caching support.

Capabilities

Basic Provider Installation

Install Basic authentication with credential configuration.

/**
 * Install Basic authentication provider
 * @param block Configuration block for BasicAuthConfig
 */
fun AuthConfig.basic(block: BasicAuthConfig.() -> Unit)

Usage Example:

install(Auth) {
    basic {
        credentials {
            // Load from secure storage or configuration
            val creds = credentialStorage.getBasicCredentials()
            BasicAuthCredentials(creds.username, creds.password)
        }
        
        sendWithoutRequest { request ->
            // Send credentials preemptively for specific hosts
            request.url.host in listOf("api.internal.com", "secure.example.com")
        }
        
        realm = "Admin Area" // Optional realm restriction
    }
}

BasicAuthCredentials Class

Container for Basic authentication credentials.

/**
 * Container for basic authentication credentials
 * @param username The username for authentication
 * @param password The password for authentication
 */
class BasicAuthCredentials(
    val username: String,
    val password: String
)

BasicAuthConfig Class

Configuration for Basic authentication provider.

/**
 * Configuration for Basic authentication
 */
class BasicAuthConfig {
    /**
     * Optional realm restriction for this provider
     */
    var realm: String?
    
    /**
     * Configure callback to load authentication credentials
     * @param block Function that returns credentials or null
     */
    fun credentials(block: suspend () -> BasicAuthCredentials?)
    
    /**
     * Configure when to send credentials without waiting for 401
     * @param block Function that returns true if credentials should be sent preemptively
     */
    fun sendWithoutRequest(block: (HttpRequestBuilder) -> Boolean)
}

The default behavior is to wait for 401 Unauthorized before sending credentials:

sendWithoutRequest { false } // Default: wait for challenge

BasicAuthProvider Class

Implementation of Basic authentication provider with credential caching.

/**
 * Basic authentication provider implementation
 */
class BasicAuthProvider(
    private val credentials: suspend () -> BasicAuthCredentials?,
    private val realm: String? = null,
    private val sendWithoutRequestCallback: (HttpRequestBuilder) -> Boolean = { false }
) : AuthProvider {
    /**
     * Clear cached credentials from memory
     * Call when credentials are updated or during logout
     * Note: This is an internal API and may change in future versions
     */
    @InternalAPI
    fun clearToken()
}

Authentication Flow

Header Format

Basic authentication uses the Authorization header with Base64-encoded credentials:

Authorization: Basic <base64(username:password)>

Example for username "admin" and password "secret":

Authorization: Basic YWRtaW46c2VjcmV0

Credential Caching

  • Credentials are loaded once and cached in memory
  • credentials callback is called only when cache is empty
  • clearToken() forces reload on next authentication attempt

Realm Handling

If a realm is specified:

  • Provider only responds to WWW-Authenticate headers with matching realm parameter
  • Multiple Basic providers can coexist with different realms

Example with realm:

WWW-Authenticate: Basic realm="Admin Area"

Usage Examples

Simple Credentials

install(Auth) {
    basic {
        credentials {
            BasicAuthCredentials("username", "password")
        }
    }
}

Environment-based Credentials

install(Auth) {
    basic {
        credentials {
            val username = System.getenv("API_USERNAME")
            val password = System.getenv("API_PASSWORD")
            if (username != null && password != null) {
                BasicAuthCredentials(username, password)
            } else {
                null // No credentials available
            }
        }
    }
}

Dynamic Credentials

install(Auth) {
    basic {
        credentials {
            // Load from database or external service
            val userSession = getCurrentUserSession()
            if (userSession?.isValid == true) {
                BasicAuthCredentials(
                    userSession.username,
                    userSession.apiKey
                )
            } else {
                null
            }
        }
        
        sendWithoutRequest { request ->
            // Only send for specific API endpoints
            request.url.encodedPath.startsWith("/api/admin/")
        }
        
        realm = "Admin API"
    }
}

Multiple Basic Providers

install(Auth) {
    // Admin API credentials
    basic {
        credentials { getAdminCredentials() }
        realm = "Admin"
    }
    
    // User API credentials  
    basic {
        credentials { getUserCredentials() }
        realm = "User"
    }
}

Security Considerations

  • HTTPS Required: Basic auth sends credentials in easily decoded Base64, always use HTTPS
  • Credential Storage: Store credentials securely using platform-specific secure storage
  • Logging: Never log username/password values in production
  • Session Management: Clear credentials on logout or session expiration
  • Realm Validation: Use realms to isolate credentials for different services

Error Scenarios

  • Missing Credentials: Request proceeds without authentication if credentials returns null
  • Invalid Credentials: Server returns 401/403, no automatic retry
  • Network Errors: Connection failures during credential loading
  • Realm Mismatch: Provider skips authentication if realm doesn't match

Limitations

  • No automatic credential refresh (unlike Bearer tokens)
  • Credentials are sent with every request (less efficient than token-based auth)
  • Base64 encoding provides no real security (encryption via HTTPS is essential)
  • Not suitable for OAuth or modern authentication flows

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