or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# Ktor JWT Authentication

1

2

Ktor JWT Authentication provides JWT (JSON Web Token) authentication functionality for Ktor server applications. It offers a comprehensive authentication plugin that supports JWT token verification using various algorithms, integrates with JWK (JSON Web Key) providers for dynamic key resolution, and provides convenient access to JWT claims through a type-safe API.

3

4

## Package Information

5

6

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

7

- **Package Type**: maven

8

- **Language**: Kotlin

9

- **Installation**: `implementation("io.ktor:ktor-server-auth-jwt-jvm:3.2.0")`

10

11

## Core Imports

12

13

```kotlin

14

import io.ktor.server.auth.jwt.*

15

import io.ktor.server.auth.*

16

import io.ktor.server.application.*

17

```

18

19

## Basic Usage

20

21

```kotlin

22

import io.ktor.server.application.*

23

import io.ktor.server.auth.*

24

import io.ktor.server.auth.jwt.*

25

import com.auth0.jwt.JWT

26

import com.auth0.jwt.algorithms.Algorithm

27

28

fun Application.configureSecurity() {

29

install(Authentication) {

30

jwt("auth-jwt") {

31

realm = "ktor sample app"

32

verifier(

33

JWT

34

.require(Algorithm.HMAC256("secret"))

35

.withAudience("jwt-audience")

36

.withIssuer("jwt-issuer")

37

.build()

38

)

39

validate { credential ->

40

if (credential.payload.audience.contains("jwt-audience")) {

41

JWTPrincipal(credential.payload)

42

} else {

43

null

44

}

45

}

46

}

47

}

48

}

49

```

50

51

## Architecture

52

53

The JWT authentication plugin integrates with Ktor's authentication pipeline through several key components:

54

55

- **Authentication Provider**: `JWTAuthenticationProvider` handles the authentication flow

56

- **Payload Holders**: `JWTCredential` and `JWTPrincipal` provide type-safe access to JWT claims

57

- **Configuration DSL**: Fluent configuration through the `jwt` function and `Config` class

58

- **Token Verification**: Supports multiple verification methods including JWK providers and static keys

59

- **Challenge Handling**: Customizable challenge responses for authentication failures

60

61

## Capabilities

62

63

### JWT Authentication Configuration

64

65

Configure JWT authentication with verifiers, validation, and challenge handling.

66

67

```kotlin { .api }

68

/**

69

* Installs the JWT Authentication provider

70

*/

71

fun AuthenticationConfig.jwt(

72

name: String? = null,

73

configure: JWTAuthenticationProvider.Config.() -> Unit

74

)

75

```

76

77

### JWT Payload Access

78

79

Base class providing convenient access to standard JWT claims and custom claims.

80

81

```kotlin { .api }

82

/**

83

* Base class for JWT credential and principal with shortcut functions for standard JWT claims

84

*/

85

abstract class JWTPayloadHolder(

86

val payload: Payload

87

) {

88

/** Gets the 'iss' (issuer) claim */

89

val issuer: String?

90

91

/** Gets the 'sub' (subject) claim */

92

val subject: String?

93

94

/** Gets the 'aud' (audience) claim as a list */

95

val audience: List<String>

96

97

/** Gets the 'exp' (expiration time) claim */

98

val expiresAt: Date?

99

100

/** Gets the 'nbf' (not before time) claim */

101

val notBefore: Date?

102

103

/** Gets the 'iat' (issued at) claim */

104

val issuedAt: Date?

105

106

/** Gets the 'jti' (JWT ID) claim */

107

val jwtId: String?

108

109

/**

110

* Gets a non-RFC JWT claim by name as a string

111

* @param name claim key as it appears in the JSON object

112

* @return claim value or null if not available or not a string

113

*/

114

operator fun get(name: String): String?

115

116

/**

117

* Gets a non-RFC JWT claim by name as the specified type

118

* @param name claim key as it appears in the JSON object

119

* @param clazz Kotlin class to deserialize the claim to

120

* @return claim value or null if not available or unable to deserialize

121

*/

122

fun <T : Any> getClaim(name: String, clazz: KClass<T>): T?

123

124

/**

125

* Gets a non-RFC JWT claim by name as a list of the specified type

126

* @param name claim key as it appears in the JSON object

127

* @param clazz Kotlin class for list elements

128

* @return claim value as list or empty list if not available or unable to deserialize

129

*/

130

fun <T : Any> getListClaim(name: String, clazz: KClass<T>): List<T>

131

}

132

```

133

134

### JWT Credential and Principal

135

136

Classes representing JWT credentials and authenticated principals.

137

138

```kotlin { .api }

139

/**

140

* JWT credential that consists of the specified payload

141

* @param payload JWT payload

142

*/

143

class JWTCredential(payload: Payload) : JWTPayloadHolder(payload)

144

145

/**

146

* JWT principal that consists of the specified payload

147

* @param payload JWT payload

148

*/

149

class JWTPrincipal(payload: Payload) : JWTPayloadHolder(payload)

150

```

151

152

### JWT Authentication Provider Configuration

153

154

Configuration options for JWT authentication including verifiers, validation, and challenge handling.

155

156

```kotlin { .api }

157

class JWTAuthenticationProvider.Config {

158

/** JWT realm to be passed in WWW-Authenticate header */

159

var realm: String

160

161

/**

162

* Configure how to retrieve HTTP authentication header

163

* @param block function that extracts auth header from ApplicationCall

164

*/

165

fun authHeader(block: (ApplicationCall) -> HttpAuthHeader?)

166

167

/**

168

* Configure authentication schemes

169

* @param defaultScheme default scheme used to challenge the client

170

* @param additionalSchemes additional schemes accepted during validation

171

*/

172

fun authSchemes(defaultScheme: String = "Bearer", vararg additionalSchemes: String)

173

174

/**

175

* Set JWT verifier instance

176

* @param verifier verifies token format and signature

177

*/

178

fun verifier(verifier: JWTVerifier)

179

180

/**

181

* Set JWT verifier function

182

* @param verifier function that returns verifier based on auth header

183

*/

184

fun verifier(verifier: (HttpAuthHeader) -> JWTVerifier?)

185

186

/**

187

* Set verifier with JWK provider and issuer

188

* @param jwkProvider provides the JSON Web Key

189

* @param issuer the issuer of the JSON Web Token

190

* @param configure function applied during JWTVerifier construction

191

*/

192

fun verifier(jwkProvider: JwkProvider, issuer: String, configure: JWTConfigureFunction = {})

193

194

/**

195

* Set verifier with JWK provider only

196

* @param jwkProvider provides the JSON Web Key

197

* @param configure function applied during JWTVerifier construction

198

*/

199

fun verifier(jwkProvider: JwkProvider, configure: JWTConfigureFunction = {})

200

201

/**

202

* Set verifier with issuer, audience and algorithm

203

* @param issuer of the JSON Web Token

204

* @param audience restriction

205

* @param algorithm for validation of token signatures

206

* @param block additional verification configuration

207

*/

208

fun verifier(

209

issuer: String,

210

audience: String,

211

algorithm: Algorithm,

212

block: Verification.() -> Unit = {}

213

)

214

215

/**

216

* Set verifier with issuer (creates JWK provider automatically)

217

* @param issuer the issuer of JSON Web Token

218

* @param block configuration of JwkProvider

219

*/

220

fun verifier(issuer: String, block: JWTConfigureFunction = {})

221

222

/**

223

* Set validation function for additional JWT payload validation

224

* @param validate function that validates JWT credential and returns principal or null

225

*/

226

fun validate(validate: suspend ApplicationCall.(JWTCredential) -> Any?)

227

228

/**

229

* Set challenge function for authentication failures

230

* @param block function that handles authentication challenges

231

*/

232

fun challenge(block: JWTAuthChallengeFunction)

233

}

234

```

235

236

### Challenge Context and Functions

237

238

Context and function types for handling authentication challenges.

239

240

```kotlin { .api }

241

/**

242

* Context for JWT authentication challenge

243

* @param call the current application call

244

*/

245

class JWTChallengeContext(

246

val call: ApplicationCall

247

)

248

249

/**

250

* Function type for JWT authentication challenge

251

*/

252

typealias JWTAuthChallengeFunction =

253

suspend JWTChallengeContext.(defaultScheme: String, realm: String) -> Unit

254

255

/**

256

* Function type for JWT verifier configuration

257

*/

258

typealias JWTConfigureFunction = Verification.() -> Unit

259

```

260

261

## Types

262

263

### External Dependencies

264

265

The JWT authentication plugin relies on these external types from the auth0 library:

266

267

```kotlin { .api }

268

// From com.auth0.jwt.interfaces

269

interface Payload {

270

val issuer: String?

271

val subject: String?

272

val audience: List<String>?

273

val expiresAt: Date?

274

val notBefore: Date?

275

val issuedAt: Date?

276

val id: String?

277

fun getClaim(name: String): Claim

278

}

279

280

interface JWTVerifier {

281

fun verify(token: String): DecodedJWT

282

}

283

284

// From com.auth0.jwt.algorithms

285

class Algorithm

286

287

// From com.auth0.jwt

288

class Verification {

289

fun build(): JWTVerifier

290

}

291

292

// From com.auth0.jwk

293

interface JwkProvider {

294

fun get(keyId: String): Jwk

295

}

296

```

297

298

### Ktor Core Types

299

300

```kotlin { .api }

301

// From io.ktor.server.application

302

interface ApplicationCall

303

304

// From io.ktor.http.auth

305

sealed class HttpAuthHeader {

306

class Single(val authScheme: String, val blob: String) : HttpAuthHeader()

307

class Parameterized(val authScheme: String, val parameters: List<HeaderValueParam>) : HttpAuthHeader()

308

}

309

310

// From io.ktor.server.auth

311

interface AuthenticationContext

312

class AuthenticationProvider

313

class AuthenticationProvider.Config

314

interface AuthenticationConfig

315

```