or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

index.mddocs/

0

# Ktor Server Authentication

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: ktor-server-auth-jvm

7

- **Package Type**: maven

8

- **Language**: Kotlin

9

- **Installation**:

10

```kotlin

11

implementation("io.ktor:ktor-server-auth-jvm:3.2.0")

12

```

13

14

## Core Imports

15

16

```kotlin

17

import io.ktor.server.auth.*

18

import io.ktor.server.application.*

19

import io.ktor.server.routing.*

20

```

21

22

## Basic Usage

23

24

```kotlin

25

import io.ktor.server.application.*

26

import io.ktor.server.auth.*

27

import io.ktor.server.routing.*

28

import io.ktor.server.response.*

29

30

fun Application.configureAuthentication() {

31

install(Authentication) {

32

basic("auth-basic") {

33

realm = "Access to the '/' path"

34

validate { credentials ->

35

if (credentials.name == "admin" && credentials.password == "password") {

36

UserIdPrincipal(credentials.name)

37

} else null

38

}

39

}

40

}

41

42

routing {

43

authenticate("auth-basic") {

44

get("/protected") {

45

val principal = call.principal<UserIdPrincipal>()

46

call.respond("Hello ${principal?.name}!")

47

}

48

}

49

}

50

}

51

```

52

53

## Architecture

54

55

The Ktor authentication module follows a provider-based architecture:

56

57

- **Authentication Plugin**: Core plugin that manages multiple authentication providers

58

- **Authentication Providers**: Specific implementations for different auth mechanisms (Basic, Bearer, OAuth, etc.)

59

- **Authentication Context**: Manages authentication state and results during request processing

60

- **Principals**: Represent authenticated users/identities

61

- **Credentials**: Represent authentication data (username/password, tokens, etc.)

62

- **Challenge System**: Handles authentication failures and response generation

63

64

## Core Components

65

66

### Authentication Plugin

67

68

Main plugin for handling authentication and authorization.

69

70

```kotlin { .api }

71

object Authentication : BaseApplicationPlugin<Application, AuthenticationConfig, Authentication>

72

73

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

74

75

class AuthenticationConfig {

76

fun provider(name: String?, configure: DynamicProviderConfig.() -> Unit)

77

fun register(provider: AuthenticationProvider)

78

}

79

80

class DynamicProviderConfig(name: String?) {

81

fun authenticate(block: (context: AuthenticationContext) -> Unit)

82

}

83

```

84

85

### Authentication Context

86

87

```kotlin { .api }

88

val ApplicationCall.authentication: AuthenticationContext

89

90

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

91

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

92

93

class AuthenticationContext {

94

fun principal(principal: Any)

95

fun principal(provider: String?, principal: Any)

96

fun <T> principal(provider: String? = null): T?

97

fun challenge(key: Any, cause: AuthenticationFailedCause, function: ChallengeFunction)

98

fun error(key: Any, cause: AuthenticationFailedCause)

99

val allErrors: List<AuthenticationFailedCause>

100

val allFailures: List<AuthenticationFailedCause>

101

}

102

```

103

104

### Route Protection

105

106

```kotlin { .api }

107

fun Route.authenticate(

108

vararg configurations: String? = arrayOf(null),

109

optional: Boolean = false,

110

build: Route.() -> Unit

111

): Route

112

113

fun Route.authenticate(

114

vararg configurations: String? = arrayOf(null),

115

strategy: AuthenticationStrategy,

116

build: Route.() -> Unit

117

): Route

118

119

enum class AuthenticationStrategy {

120

Optional, FirstSuccessful, Required

121

}

122

123

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

124

125

object AuthenticationChecked

126

```

127

128

## Capabilities

129

130

### Basic Authentication

131

132

HTTP Basic authentication with username and password validation.

133

134

```kotlin { .api }

135

fun AuthenticationConfig.basic(

136

name: String? = null,

137

configure: BasicAuthenticationProvider.Config.() -> Unit

138

)

139

```

140

141

[Basic Authentication](./basic-auth.md)

142

143

### Bearer Token Authentication

144

145

Bearer token authentication for API access tokens and JWT tokens.

146

147

```kotlin { .api }

148

fun AuthenticationConfig.bearer(

149

name: String? = null,

150

configure: BearerAuthenticationProvider.Config.() -> Unit

151

)

152

```

153

154

[Bearer Authentication](./bearer-auth.md)

155

156

### Form and Session Authentication

157

158

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

159

160

```kotlin { .api }

161

fun AuthenticationConfig.form(

162

name: String? = null,

163

configure: FormAuthenticationProvider.Config.() -> Unit

164

)

165

166

fun <T : Any> AuthenticationConfig.session(

167

name: String? = null,

168

configure: SessionAuthenticationProvider.Config<T>.() -> Unit

169

)

170

```

171

172

[Form and Session Authentication](./form-session-auth.md)

173

174

### OAuth Authentication

175

176

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

177

178

```kotlin { .api }

179

fun AuthenticationConfig.oauth(

180

name: String? = null,

181

configure: OAuthAuthenticationProvider.Config.() -> Unit

182

)

183

```

184

185

[OAuth Authentication](./oauth.md)

186

187

### JVM-Specific Features

188

189

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

190

191

```kotlin { .api }

192

fun AuthenticationConfig.digest(

193

name: String? = null,

194

configure: DigestAuthenticationProvider.Config.() -> Unit

195

)

196

```

197

198

[JVM-Specific Features](./jvm-features.md)

199

200

## Common Types

201

202

### Credentials

203

204

```kotlin { .api }

205

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

206

data class BearerTokenCredential(val token: String)

207

```

208

209

### Principals

210

211

```kotlin { .api }

212

data class UserIdPrincipal(val name: String)

213

```

214

215

### Utility Classes

216

217

```kotlin { .api }

218

class UserHashedTableAuth(

219

table: Map<String, ByteArray>,

220

digester: (String) -> String

221

) {

222

fun authenticate(credential: UserPasswordCredential): UserIdPrincipal?

223

}

224

```

225

226

### Header Utilities

227

228

```kotlin { .api }

229

fun ApplicationRequest.parseAuthorizationHeader(): HttpAuthHeader?

230

```

231

232

### Authentication Results

233

234

```kotlin { .api }

235

sealed class AuthenticationFailedCause {

236

data object NoCredentials : AuthenticationFailedCause()

237

data object InvalidCredentials : AuthenticationFailedCause()

238

open class Error(val message: String) : AuthenticationFailedCause()

239

}

240

241

typealias ChallengeFunction = suspend PipelineContext<*, ApplicationCall>.(String, String) -> Unit

242

typealias AuthenticationFunction<C> = suspend ApplicationCall.(C) -> Any?

243

typealias ApplicationCallPredicate = (ApplicationCall) -> Boolean

244

```

245

246

### Response Types

247

248

```kotlin { .api }

249

class UnauthorizedResponse(

250

challenge: HttpAuthHeader = HttpAuthHeader.basicAuthChallenge("Ktor Server")

251

) : HttpStatusCodeContent

252

253

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

254

```

255

256

## Platform Availability

257

258

- **Common**: Basic, Bearer, Form, Session authentication, OAuth 2.0

259

- **JVM Only**: Digest authentication, OAuth 1.0a

260

- **JS/WASM/Native**: Limited OAuth support through platform-specific implementations