(O+P)ut

アウトプット



(O+P)ut

エンジニアのアウトプット

【Keycloak/RHBK】jqコマンドを利用してGETするユーザを属性の値で絞る

スポンサーリンク

やりたいこと

Red Hat build of Keycloak(Keycloakの商用版)にてAdmin API経由でリスト表示するユーザを絞る。
具体的には属性hogeの値がfugaのユーザのみの出力を行う。

環境情報
  • Red Hat Enterprise Linux : 9.3 (Plow)
  • rhbk-22.0.8

やり方

アクセストークンの取得を行い

$ AT=`curl --insecure -X POST http://localhost:8080/realms/master/protocol/openid-connect/token --user admin-cli:admin -H 'content-type: application/x-www-form-urlencoded' -d 'username=admin&password=xx&grant_type=password' | jq .access_token | sed -e 's/"//g'`

jqコマンドにてselect(.attributes.[] == を利用することで条件を元に抽出する。

$ curl -k -X GET http://localhost:8080/admin/realms/master/users -H "Authorization: Bearer "$AT | jq -r '.[] | select(.attributes.hoge[] == "fuga") | .username'
...
test01
test02

以下、補足です。

補足

Keycloakでは以下のようにGUIにてユーザへ属性を付与でき

属性の付与画面
CUIでも以下のように行えます。

$ curl --location --request PUT 'http://localhost:8080/admin/realms/master/users/<id> --header 'Content-Type: application/json' --header "Authorization: Bearer $AT" --data-raw '{"attributes": {"hoge":["fuga"]}}'

そして、これらの値はJSONでは以下のように格納されているので

 {
    "id": "xx",
    "createdTimestamp": xx,
    "username": "test01",
    "enabled": true,
    "totp": false,
    "emailVerified": false,
    "attributes": {
      "hoge": [
        "fuga"
      ]
    },

上記で記載したように抽出を行えました。

注意点としてはattributesの検索条件に指定したkeyを持っていないユーザがいる場合は

jq: error (at <stdin>:0): Cannot iterate over null (null)

というエラーになるので、その場合は同抽出条件は利用できません。

尚、jqコマンドによる検索条件を使うことで例えば属性の値ではなく値の文字数等でも抽出を行うこともできます。

$  curl -k -X GET http://localhost:8080/admin/realms/master/users -H "Authorization: Bearer "$AT | jq -r '.[] | select(.attributes.hoge[] | length == 3) | .username'

以上。