You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过API在Keycloak 22.0.3中创建启用状态的用户?

Keycloak 22.0.3 API创建用户:禁用状态与凭据未保存问题

问题描述

通过API调用在Keycloak 22.0.3服务器中创建新用户,代码可正常创建用户并将其添加到指定组,但新创建的用户处于禁用状态,且凭据未被保存。API调用序列如下:

// 创建用户请求
URL: https://localhost:8080/admin/realms/MyRealm/users
options: {
  "headers": {
    "Authorization": "Bearer ey...",
    "Content-Type": "application/json"
  },
  "method": "POST",
  "body": "{\"email\":\"marioross12i@example.com\",\"username\":\"mariorossi12\",\"attributes\":{\"provisioned\":true},\"credentials\":[{\"secretData\":\"changeme\",\"temporary\":true}]}"
}

// 清除暴力检测记录请求
URL: https://localhost:8080/admin/realms/MyRealm/attack-detection/brute-force/users/fe3d9e63-cd24-423f-a620-2027f907a9ca
options: {
  "headers": {
    "Authorization": "Bearer ey...",
    "Content-Type": "application/x-www-form-urlencoded"
  },
  "method": "DELETE"
}

// 添加用户到组请求
URL: https://localhost:8080/admin/realms/MyRealm/users/fe3d9e63-cd24-423f-a620-2027f907a9ca/groups/97788f9e-a113-420b-a629-ad39e5d70f09
options: {
  "headers": {
    "Authorization": "Bearer ey...",
    "Content-Type": "application/x-www-form-urlencoded"
  },
  "method": "PUT"
}

问题原因及解决方案

1. 用户处于禁用状态的原因

Keycloak创建用户时,若未显式指定enabled字段,默认会将用户设置为禁用状态(enabled: false)。你的创建请求体中缺少该字段,导致用户被禁用。

解决方法:在创建用户的POST请求体中添加"enabled": true字段。

2. 凭据未保存的原因

你使用了错误的凭据字段结构:

  • 错误地使用secretData字段存储密码,该字段是Keycloak内部加密存储的字段,不是用来设置明文密码的
  • 缺少type字段(必须指定凭据类型,通常为password)

解决方法:调整凭据数组的结构,使用type和value字段定义密码,示例如下:

{
  "email": "marioross12i@example.com",
  "username": "mariorossi12",
  "attributes": { "provisioned": true },
  "credentials": [
    {
      "type": "password",
      "value": "changeme",
      "temporary": true
    }
  ],
  "enabled": true
}

验证效果

使用修改后的请求体创建用户后,用户会处于启用状态,密码凭据也会被正确存储到Keycloak中,同时用户首次登录时会被要求修改临时密码(因为temporary: true)。

内容的提问来源于stack exchange,提问作者Lucio Crusca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 11:45:20