0
# Basic Authentication
1
2
Username/password authentication using HTTP Basic authentication scheme. Suitable for simple authentication scenarios and internal APIs with credential caching support.
3
4
## Capabilities
5
6
### Basic Provider Installation
7
8
Install Basic authentication with credential configuration.
9
10
```kotlin { .api }
11
/**
12
* Install Basic authentication provider
13
* @param block Configuration block for BasicAuthConfig
14
*/
15
fun AuthConfig.basic(block: BasicAuthConfig.() -> Unit)
16
```
17
18
**Usage Example:**
19
20
```kotlin
21
install(Auth) {
22
basic {
23
credentials {
24
// Load from secure storage or configuration
25
val creds = credentialStorage.getBasicCredentials()
26
BasicAuthCredentials(creds.username, creds.password)
27
}
28
29
sendWithoutRequest { request ->
30
// Send credentials preemptively for specific hosts
31
request.url.host in listOf("api.internal.com", "secure.example.com")
32
}
33
34
realm = "Admin Area" // Optional realm restriction
35
}
36
}
37
```
38
39
### BasicAuthCredentials Class
40
41
Container for Basic authentication credentials.
42
43
```kotlin { .api }
44
/**
45
* Container for basic authentication credentials
46
* @param username The username for authentication
47
* @param password The password for authentication
48
*/
49
class BasicAuthCredentials(
50
val username: String,
51
val password: String
52
)
53
```
54
55
### BasicAuthConfig Class
56
57
Configuration for Basic authentication provider.
58
59
```kotlin { .api }
60
/**
61
* Configuration for Basic authentication
62
*/
63
class BasicAuthConfig {
64
/**
65
* Optional realm restriction for this provider
66
*/
67
var realm: String?
68
69
/**
70
* Configure callback to load authentication credentials
71
* @param block Function that returns credentials or null
72
*/
73
fun credentials(block: suspend () -> BasicAuthCredentials?)
74
75
/**
76
* Configure when to send credentials without waiting for 401
77
* @param block Function that returns true if credentials should be sent preemptively
78
*/
79
fun sendWithoutRequest(block: (HttpRequestBuilder) -> Boolean)
80
}
81
```
82
83
The default behavior is to wait for 401 Unauthorized before sending credentials:
84
85
```kotlin
86
sendWithoutRequest { false } // Default: wait for challenge
87
```
88
89
### BasicAuthProvider Class
90
91
Implementation of Basic authentication provider with credential caching.
92
93
```kotlin { .api }
94
/**
95
* Basic authentication provider implementation
96
*/
97
class BasicAuthProvider(
98
private val credentials: suspend () -> BasicAuthCredentials?,
99
private val realm: String? = null,
100
private val sendWithoutRequestCallback: (HttpRequestBuilder) -> Boolean = { false }
101
) : AuthProvider {
102
/**
103
* Clear cached credentials from memory
104
* Call when credentials are updated or during logout
105
* Note: This is an internal API and may change in future versions
106
*/
107
@InternalAPI
108
fun clearToken()
109
}
110
```
111
112
## Authentication Flow
113
114
### Header Format
115
116
Basic authentication uses the Authorization header with Base64-encoded credentials:
117
118
```
119
Authorization: Basic <base64(username:password)>
120
```
121
122
Example for username "admin" and password "secret":
123
```
124
Authorization: Basic YWRtaW46c2VjcmV0
125
```
126
127
### Credential Caching
128
129
- Credentials are loaded once and cached in memory
130
- `credentials` callback is called only when cache is empty
131
- `clearToken()` forces reload on next authentication attempt
132
133
### Realm Handling
134
135
If a realm is specified:
136
- Provider only responds to WWW-Authenticate headers with matching realm parameter
137
- Multiple Basic providers can coexist with different realms
138
139
**Example with realm:**
140
```
141
WWW-Authenticate: Basic realm="Admin Area"
142
```
143
144
## Usage Examples
145
146
### Simple Credentials
147
148
```kotlin
149
install(Auth) {
150
basic {
151
credentials {
152
BasicAuthCredentials("username", "password")
153
}
154
}
155
}
156
```
157
158
### Environment-based Credentials
159
160
```kotlin
161
install(Auth) {
162
basic {
163
credentials {
164
val username = System.getenv("API_USERNAME")
165
val password = System.getenv("API_PASSWORD")
166
if (username != null && password != null) {
167
BasicAuthCredentials(username, password)
168
} else {
169
null // No credentials available
170
}
171
}
172
}
173
}
174
```
175
176
### Dynamic Credentials
177
178
```kotlin
179
install(Auth) {
180
basic {
181
credentials {
182
// Load from database or external service
183
val userSession = getCurrentUserSession()
184
if (userSession?.isValid == true) {
185
BasicAuthCredentials(
186
userSession.username,
187
userSession.apiKey
188
)
189
} else {
190
null
191
}
192
}
193
194
sendWithoutRequest { request ->
195
// Only send for specific API endpoints
196
request.url.encodedPath.startsWith("/api/admin/")
197
}
198
199
realm = "Admin API"
200
}
201
}
202
```
203
204
### Multiple Basic Providers
205
206
```kotlin
207
install(Auth) {
208
// Admin API credentials
209
basic {
210
credentials { getAdminCredentials() }
211
realm = "Admin"
212
}
213
214
// User API credentials
215
basic {
216
credentials { getUserCredentials() }
217
realm = "User"
218
}
219
}
220
```
221
222
## Security Considerations
223
224
- **HTTPS Required**: Basic auth sends credentials in easily decoded Base64, always use HTTPS
225
- **Credential Storage**: Store credentials securely using platform-specific secure storage
226
- **Logging**: Never log username/password values in production
227
- **Session Management**: Clear credentials on logout or session expiration
228
- **Realm Validation**: Use realms to isolate credentials for different services
229
230
## Error Scenarios
231
232
- **Missing Credentials**: Request proceeds without authentication if `credentials` returns null
233
- **Invalid Credentials**: Server returns 401/403, no automatic retry
234
- **Network Errors**: Connection failures during credential loading
235
- **Realm Mismatch**: Provider skips authentication if realm doesn't match
236
237
## Limitations
238
239
- No automatic credential refresh (unlike Bearer tokens)
240
- Credentials are sent with every request (less efficient than token-based auth)
241
- Base64 encoding provides no real security (encryption via HTTPS is essential)
242
- Not suitable for OAuth or modern authentication flows