or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

attack-detection.mdauthentication-management.mdcache-management.mdclient-configuration.mdclient-management.mdclient-policies.mdclient-scopes.mdcomponents.mdgroup-management.mdidentity-providers.mdindex.mdorganization-management.mdrealm-management.mdrole-management.mdserver-info.mduser-management.mduser-storage-provider.mdutility-functions.mdwhoami.md
tile.json

client-configuration.mddocs/

0

# Client Configuration and Authentication

1

2

The KeycloakAdminClient class serves as the main entry point for all administrative operations. It handles authentication, token management, and provides access to all resource endpoints.

3

4

## Capabilities

5

6

### KeycloakAdminClient Class

7

8

The main client class that initializes all resource endpoints and manages connection configuration.

9

10

```typescript { .api }

11

/**

12

* Main Keycloak Admin Client class providing access to all administrative functionality

13

*/

14

class KeycloakAdminClient {

15

// Resource instances - all Keycloak API endpoints

16

public users: Users;

17

public userStorageProvider: UserStorageProvider;

18

public groups: Groups;

19

public roles: Roles;

20

public organizations: Organizations;

21

public clients: Clients;

22

public realms: Realms;

23

public clientScopes: ClientScopes;

24

public clientPolicies: ClientPolicies;

25

public identityProviders: IdentityProviders;

26

public components: Components;

27

public serverInfo: ServerInfo;

28

public whoAmI: WhoAmI;

29

public attackDetection: AttackDetection;

30

public authenticationManagement: AuthenticationManagement;

31

public cache: Cache;

32

33

// Connection settings

34

public baseUrl: string;

35

public realmName: string;

36

public scope?: string;

37

public accessToken?: string;

38

public refreshToken?: string;

39

40

/**

41

* Initialize Keycloak Admin Client

42

* @param connectionConfig - Optional configuration for connection settings

43

*/

44

constructor(connectionConfig?: ConnectionConfig);

45

46

// Authentication methods

47

auth(credentials: Credentials): Promise<void>;

48

registerTokenProvider(provider: TokenProvider): void;

49

setAccessToken(token: string): void;

50

getAccessToken(): Promise<string | undefined>;

51

52

// Configuration methods

53

setConfig(connectionConfig: ConnectionConfig): void;

54

getRequestOptions(): RequestInit | undefined;

55

getGlobalRequestArgOptions(): Pick<RequestArgs, "catchNotFound"> | undefined;

56

}

57

```

58

59

**Usage Examples:**

60

61

```typescript

62

import KeycloakAdminClient from "@keycloak/keycloak-admin-client";

63

64

// Basic initialization

65

const kcAdminClient = new KeycloakAdminClient();

66

67

// With custom configuration

68

const kcAdminClient = new KeycloakAdminClient({

69

baseUrl: "https://keycloak.example.com",

70

realmName: "my-realm",

71

requestOptions: {

72

headers: {

73

"Custom-Header": "value",

74

},

75

timeout: 10000,

76

},

77

requestArgOptions: {

78

catchNotFound: true, // Return undefined instead of throwing on 404

79

},

80

});

81

82

// Access resources

83

const users = await kcAdminClient.users.find();

84

const realms = await kcAdminClient.realms.find();

85

```

86

87

### Connection Configuration

88

89

Configuration interface for customizing client connection behavior.

90

91

```typescript { .api }

92

/**

93

* Configuration options for Keycloak Admin Client connection

94

*/

95

interface ConnectionConfig {

96

/** Base URL of Keycloak server (default: "http://127.0.0.1:8180") */

97

baseUrl?: string;

98

/** Realm name for authentication and operations (default: "master") */

99

realmName?: string;

100

/** Custom request options passed to all HTTP calls */

101

requestOptions?: RequestInit;

102

/** Global options for request arguments */

103

requestArgOptions?: Pick<RequestArgs, "catchNotFound">;

104

}

105

106

/**

107

* Request argument options for customizing API behavior

108

*/

109

interface RequestArgs {

110

/** Return undefined instead of throwing NetworkError on 404 responses */

111

catchNotFound?: boolean;

112

}

113

```

114

115

### Authentication

116

117

Multiple authentication methods for different use cases and deployment scenarios.

118

119

```typescript { .api }

120

/**

121

* Authenticate using credentials and obtain access token

122

* @param credentials - Authentication credentials with grant type

123

*/

124

auth(credentials: Credentials): Promise<void>;

125

126

/**

127

* Supported OAuth2 grant types for authentication

128

*/

129

type GrantTypes = "client_credentials" | "password" | "refresh_token";

130

131

/**

132

* Authentication credentials for different grant types

133

*/

134

interface Credentials {

135

/** Username for password grant type */

136

username?: string;

137

/** Password for password grant type */

138

password?: string;

139

/** OAuth2 grant type */

140

grantType: GrantTypes;

141

/** Client ID for authentication */

142

clientId: string;

143

/** Client secret for confidential clients */

144

clientSecret?: string;

145

/** TOTP code for two-factor authentication */

146

totp?: string;

147

/** Request offline token for refresh capability */

148

offlineToken?: boolean;

149

/** Refresh token for refresh_token grant type */

150

refreshToken?: string;

151

/** OAuth2 scopes to request */

152

scopes?: string[];

153

}

154

```

155

156

**Authentication Examples:**

157

158

```typescript

159

// Username/password authentication (admin-cli client)

160

await kcAdminClient.auth({

161

username: "admin",

162

password: "admin",

163

grantType: "password",

164

clientId: "admin-cli",

165

});

166

167

// Client credentials authentication (service account)

168

await kcAdminClient.auth({

169

grantType: "client_credentials",

170

clientId: "my-service-client",

171

clientSecret: "client-secret-here",

172

});

173

174

// Refresh token authentication

175

await kcAdminClient.auth({

176

grantType: "refresh_token",

177

clientId: "admin-cli",

178

refreshToken: "refresh-token-here",

179

});

180

181

// Authentication with custom scopes

182

await kcAdminClient.auth({

183

username: "admin",

184

password: "admin",

185

grantType: "password",

186

clientId: "admin-cli",

187

scopes: ["openid", "profile", "email"],

188

});

189

```

190

191

### Token Management

192

193

Advanced token handling for custom authentication flows and external token sources.

194

195

```typescript { .api }

196

/**

197

* Custom token provider interface for external authentication

198

*/

199

interface TokenProvider {

200

/** Function to retrieve access token from external source */

201

getAccessToken: () => Promise<string | undefined>;

202

}

203

204

/**

205

* Register custom token provider for external authentication

206

* @param provider - Token provider implementation

207

*/

208

registerTokenProvider(provider: TokenProvider): void;

209

210

/**

211

* Manually set access token (bypasses authentication)

212

* @param token - JWT access token

213

*/

214

setAccessToken(token: string): void;

215

216

/**

217

* Get current access token (from auth or token provider)

218

* @returns Current access token or undefined

219

*/

220

getAccessToken(): Promise<string | undefined>;

221

```

222

223

**Token Management Examples:**

224

225

```typescript

226

// Custom token provider (e.g., from external auth system)

227

kcAdminClient.registerTokenProvider({

228

getAccessToken: async () => {

229

// Fetch token from your auth system

230

const response = await fetch("/api/keycloak-token");

231

const { token } = await response.json();

232

return token;

233

},

234

});

235

236

// Manual token management

237

const externalToken = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...";

238

kcAdminClient.setAccessToken(externalToken);

239

240

// Check current token

241

const currentToken = await kcAdminClient.getAccessToken();

242

if (!currentToken) {

243

// Re-authenticate if needed

244

await kcAdminClient.auth(credentials);

245

}

246

```

247

248

### Configuration Management

249

250

Runtime configuration updates and request customization.

251

252

```typescript { .api }

253

/**

254

* Update client configuration at runtime

255

* @param connectionConfig - New connection configuration

256

*/

257

setConfig(connectionConfig: ConnectionConfig): void;

258

259

/**

260

* Get current request options for HTTP calls

261

* @returns Current RequestInit options or undefined

262

*/

263

getRequestOptions(): RequestInit | undefined;

264

265

/**

266

* Get global request argument options

267

* @returns Current request argument options or undefined

268

*/

269

getGlobalRequestArgOptions(): Pick<RequestArgs, "catchNotFound"> | undefined;

270

```

271

272

**Configuration Examples:**

273

274

```typescript

275

// Update configuration at runtime

276

kcAdminClient.setConfig({

277

baseUrl: "https://new-keycloak-server.com",

278

realmName: "production-realm",

279

requestOptions: {

280

timeout: 30000,

281

headers: {

282

"X-Request-ID": generateRequestId(),

283

},

284

},

285

});

286

287

// Check current configuration

288

const requestOptions = kcAdminClient.getRequestOptions();

289

const argOptions = kcAdminClient.getGlobalRequestArgOptions();

290

```

291

292

### Authentication Response

293

294

Token response structure returned by the authentication process.

295

296

```typescript { .api }

297

/**

298

* Response from successful authentication containing tokens and metadata

299

*/

300

interface TokenResponse {

301

/** JWT access token for API authentication */

302

accessToken: string;

303

/** Token expiration time in seconds */

304

expiresIn: string;

305

/** Refresh token expiration time in seconds */

306

refreshExpiresIn: number;

307

/** Refresh token for obtaining new access tokens */

308

refreshToken: string;

309

/** Token type (typically "Bearer") */

310

tokenType: string;

311

/** Not-before policy timestamp */

312

notBeforePolicy: number;

313

/** Session state identifier */

314

sessionState: string;

315

/** OAuth2 scope granted */

316

scope: string;

317

/** Optional OpenID Connect ID token */

318

idToken?: string;

319

}

320

```

321

322

### Error Handling

323

324

The client automatically handles authentication errors and token expiration.

325

326

```typescript

327

try {

328

await kcAdminClient.auth({

329

username: "invalid-user",

330

password: "wrong-password",

331

grantType: "password",

332

clientId: "admin-cli",

333

});

334

} catch (error) {

335

if (error instanceof NetworkError) {

336

// Handle authentication failure

337

console.log("Authentication failed:", error.response.status);

338

console.log("Error details:", error.responseData);

339

}

340

}

341

```