且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过ID获取其他用户的信息(用户名,名字)? [钥匙斗篷]

更新时间:2023-01-29 23:07:55

您可以使用Admin REST API.有关API的详细说明,可此处.您也可以使用JAVA包装器API.请在下面找到几个示例.

You can use the Admin REST API. The detailed description of the relevant API is available here. Also you can use the JAVA wrapper API. Please find couple of examples below.

示例1,REST:

获取访问令牌:

curl \
  -d "client_id=admin-cli" \
  -d "username=admin" \
  -d "password=secret" \
  -d "grant_type=password" \
  "http://localhost:8080/auth/realms/master/protocol/openid-connect/token"

获取所有用户:

curl \
  -H "Authorization: bearer eyJhbGciOiJSUzI...." \
  "http://localhost:8080/auth/admin/realms/master/users"

示例输出:

[
     {
        "id":"349f67de-36e6-4552-ac54-e52085109616",
        "username":"admin",
        "enabled":true,
        ...
     },
     {
        "id":"08afb701-fae5-40b4-8895-e387ba1902fb",
        "username":"lbalev",
        "enabled":true,
        ....
     }
  ]

通过用户ID获取用户:

Get a user based by user id:

curl \
  -H "Authorization: bearer eyJhbGciOiJSU...." \
  "http://localhost:8080/auth/admin/realms/master/users/349f67de-36e6-4552-ac54-e52085109616"

示例2,JAVA API:

根据二手ID获取二手:

Get a used based on used ID:

public class TestUserAccess {

  private static final String SERVER_URL = "http://localhost:8080/auth";
  private static final String REALM = "master";
  private static final String USERNAME = "admin";
  private static final String PASSWORD = "secret";
  private static final String CLIENT_ID = "admin-cli";

  public static void main(String[] args) {

    Keycloak keycloak = KeycloakBuilder
        .builder()
        .serverUrl(SERVER_URL)
        .realm(REALM)
        .username(USERNAME)
        .password(PASSWORD)
        .clientId(CLIENT_ID)
        .resteasyClient(new ResteasyClientBuilder().connectionPoolSize(10).build())
        .build();

    UsersResource usersResource = keycloak.realm(REALM).users();
    UserResource userResource = usersResource.get("08afb701-fae5-40b4-8895-e387ba1902fb");
    System.out.println(userResource.toRepresentation().getEmail());
  }
}

上面示例的相关依赖项为(请注意,这些版本可能不是最新的):

The relevant dependencies for the example above are (please note that the versions might not be up-to-date):

dependencies {
    compile group: 'org.keycloak', name: 'keycloak-admin-client', version: '3.3.0.CR2'
    compile group: 'org.jboss.resteasy', name: 'resteasy-jaxrs', version: '3.1.4.Final'
    compile group: 'org.jboss.resteasy', name: 'resteasy-client', version: '3.1.4.Final'
    compile group: 'org.jboss.resteasy', name: 'resteasy-jackson2-provider', version: '3.1.4.Final'
}