or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

auth-plugin.mdbasic-auth.mdbearer-auth.mddigest-auth.mdindex.md

auth-plugin.mddocs/

0

# Auth Plugin

1

2

Core authentication plugin for Ktor HTTP clients that manages authentication providers and handles the authentication flow automatically.

3

4

## Capabilities

5

6

### Auth Plugin Installation

7

8

Install the Auth plugin with configuration for authentication providers and unauthorized response detection.

9

10

```kotlin { .api }

11

/**

12

* Install Auth plugin with configuration

13

* @param block Configuration block for AuthConfig

14

*/

15

fun HttpClientConfig<*>.Auth(block: AuthConfig.() -> Unit)

16

17

/**

18

* Core authentication plugin instance

19

*/

20

val Auth: ClientPlugin<AuthConfig>

21

```

22

23

**Usage Example:**

24

25

```kotlin

26

import io.ktor.client.*

27

import io.ktor.client.engine.cio.*

28

import io.ktor.client.plugins.auth.*

29

import io.ktor.client.plugins.auth.providers.*

30

31

val client = HttpClient(CIO) {

32

install(Auth) {

33

// Configure authentication providers

34

bearer { /* bearer config */ }

35

basic { /* basic config */ }

36

37

// Optional: customize unauthorized response detection

38

reAuthorizeOnResponse { response ->

39

response.status == HttpStatusCode.Unauthorized ||

40

response.status == HttpStatusCode.Forbidden

41

}

42

}

43

}

44

```

45

46

### AuthConfig Class

47

48

Configuration class for the Auth plugin containing provider management and response detection.

49

50

```kotlin { .api }

51

/**

52

* Configuration for Auth plugin

53

*/

54

class AuthConfig {

55

/**

56

* List of authentication providers to use

57

*/

58

val providers: MutableList<AuthProvider>

59

60

/**

61

* Set custom function to detect unauthorized responses

62

* @param block Function that returns true if response should trigger re-auth

63

*/

64

fun reAuthorizeOnResponse(block: suspend (HttpResponse) -> Boolean)

65

}

66

```

67

68

The default unauthorized response detector checks for HTTP 401 status code:

69

70

```kotlin

71

// Default implementation

72

isUnauthorizedResponse = { it.status == HttpStatusCode.Unauthorized }

73

```

74

75

### Circuit Breaker

76

77

Attribute key used to prevent infinite authentication loops by marking requests that should skip authentication.

78

79

```kotlin { .api }

80

/**

81

* Attribute key to mark requests that should skip auth procedures

82

*/

83

val AuthCircuitBreaker: AttributeKey<Unit>

84

```

85

86

**Usage Example:**

87

88

```kotlin

89

// Mark a request to skip authentication (e.g., token refresh request)

90

val request = HttpRequestBuilder().apply {

91

attributes.put(AuthCircuitBreaker, Unit)

92

}

93

```

94

95

### HttpClient Extensions

96

97

Extension functions for accessing configured authentication providers.

98

99

```kotlin { .api }

100

/**

101

* Get list of all configured authentication providers

102

*/

103

val HttpClient.authProviders: List<AuthProvider>

104

105

/**

106

* Get specific authentication provider by type

107

* @return Provider instance or null if not found

108

*/

109

inline fun <reified T : AuthProvider> HttpClient.authProvider(): T?

110

```

111

112

**Usage Examples:**

113

114

```kotlin

115

// Get all providers

116

val allProviders = client.authProviders

117

118

// Get specific provider type

119

val bearerProvider = client.authProvider<BearerAuthProvider>()

120

bearerProvider?.clearToken() // Clear cached tokens if needed

121

122

// Check if Basic auth is configured

123

val hasBasicAuth = client.authProvider<BasicAuthProvider>() != null

124

```

125

126

## Authentication Flow

127

128

The Auth plugin follows this automatic flow:

129

130

1. **Request Interception**: Providers that send without waiting for 401 add headers preemptively

131

2. **Response Analysis**: If response is unauthorized, find applicable provider based on WWW-Authenticate header

132

3. **Token Refresh**: Attempt to refresh tokens if provider supports it

133

4. **Retry Request**: Add authentication headers and retry the request

134

5. **Circuit Breaking**: Prevent infinite loops by tracking request attributes

135

136

## Error Handling

137

138

The Auth plugin handles various error scenarios:

139

140

- **No WWW-Authenticate Header**: Logs warning and uses single provider if available

141

- **No Applicable Provider**: Returns original response without retry

142

- **Refresh Failure**: Returns original response if token refresh fails

143

- **Infinite Loops**: Circuit breaker prevents repeated authentication attempts