0
# Basic Authentication
1
2
HTTP Basic authentication provider supporting username/password credentials with optional realm specification, configurable sending behavior, and automatic credential caching with token management.
3
4
## Capabilities
5
6
### Basic Authentication Provider Installation
7
8
Install the Basic authentication provider with configuration.
9
10
```kotlin { .api }
11
/**
12
* Installs the client's BasicAuthProvider
13
* @param block Configuration block for Basic authentication
14
*/
15
fun AuthConfig.basic(block: BasicAuthConfig.() -> Unit)
16
```
17
18
**Usage Example:**
19
20
```kotlin
21
import io.ktor.client.*
22
import io.ktor.client.plugins.auth.*
23
import io.ktor.client.plugins.auth.providers.*
24
25
val client = HttpClient {
26
Auth {
27
basic {
28
credentials {
29
BasicAuthCredentials("username", "password")
30
}
31
realm = "MyRealm"
32
}
33
}
34
}
35
```
36
37
### Basic Authentication Configuration
38
39
Configuration class for BasicAuthProvider with credential management and sending behavior control.
40
41
```kotlin { .api }
42
/**
43
* Configuration for BasicAuthProvider
44
*/
45
class BasicAuthConfig {
46
/**
47
* Optional realm specification for the current provider
48
*/
49
var realm: String?
50
51
/**
52
* Configures authentication credentials provider
53
* @param block Suspend function that returns credentials or null
54
*/
55
fun credentials(block: suspend () -> BasicAuthCredentials?)
56
57
/**
58
* Configures when to send credentials without waiting for HttpStatusCode.Unauthorized
59
* @param block Function that determines based on request whether to send credentials proactively
60
*/
61
fun sendWithoutRequest(block: (HttpRequestBuilder) -> Boolean)
62
}
63
```
64
65
**Usage Examples:**
66
67
```kotlin
68
basic {
69
// Static credentials
70
credentials {
71
BasicAuthCredentials("user", "pass")
72
}
73
74
// Dynamic credentials
75
credentials {
76
val token = loadFromSecureStorage()
77
if (token != null) BasicAuthCredentials(token.username, token.password)
78
else null
79
}
80
81
// Send credentials proactively for specific paths
82
sendWithoutRequest { request ->
83
request.url.encodedPath.startsWith("/api/")
84
}
85
86
realm = "ProtectedArea"
87
}
88
```
89
90
### Basic Authentication Credentials
91
92
Container class for Basic authentication credentials.
93
94
```kotlin { .api }
95
/**
96
* Contains credentials for BasicAuthProvider
97
* @param username Username for authentication
98
* @param password Password for authentication
99
*/
100
class BasicAuthCredentials(
101
val username: String,
102
val password: String
103
)
104
```
105
106
### Basic Authentication Provider
107
108
Authentication provider implementation for the Basic HTTP authentication scheme.
109
110
```kotlin { .api }
111
/**
112
* Authentication provider for the Basic HTTP authentication scheme
113
* The Basic authentication scheme can be used for logging in users
114
*/
115
class BasicAuthProvider(
116
private val credentials: suspend () -> BasicAuthCredentials?,
117
private val realm: String? = null,
118
private val sendWithoutRequestCallback: (HttpRequestBuilder) -> Boolean = { false }
119
) : AuthProvider {
120
121
// Note: clearToken() method is available but marked as @InternalAPI
122
123
override fun sendWithoutRequest(request: HttpRequestBuilder): Boolean
124
override fun isApplicable(auth: HttpAuthHeader): Boolean
125
override suspend fun addRequestHeaders(request: HttpRequestBuilder, authHeader: HttpAuthHeader?)
126
override suspend fun refreshToken(response: HttpResponse): Boolean
127
}
128
```
129
130
**Usage Examples:**
131
132
```kotlin
133
import io.ktor.client.*
134
import io.ktor.client.plugins.auth.*
135
import io.ktor.client.plugins.auth.providers.*
136
137
// Basic setup with static credentials
138
val client = HttpClient {
139
Auth {
140
basic {
141
credentials {
142
BasicAuthCredentials("alice", "password123")
143
}
144
}
145
}
146
}
147
148
// Advanced setup with realm and conditional sending
149
val advancedClient = HttpClient {
150
Auth {
151
basic {
152
credentials {
153
// Load from secure storage or user input
154
loadCredentialsFromStorage()
155
}
156
realm = "AdminArea"
157
sendWithoutRequest { request ->
158
// Only send for admin API paths
159
request.url.encodedPath.startsWith("/admin/")
160
}
161
}
162
}
163
}
164
165
// Note: clearToken() is available as internal API for clearing cached credentials
166
```
167
168
## Authentication Flow
169
170
1. **Initial Request**: If `sendWithoutRequest` returns `true`, credentials are added proactively
171
2. **401 Response**: When server responds with 401 Unauthorized, provider checks `isApplicable()`
172
3. **Realm Matching**: Provider validates realm from WWW-Authenticate header matches configured realm
173
4. **Token Refresh**: `refreshToken()` is called to refresh cached credentials
174
5. **Retry Request**: Request is retried with authentication headers
175
6. **Circuit Breaker**: If request contains `AuthCircuitBreaker` attribute, authentication is skipped