21

標準のwildflyベースのKeycloakアダプターを使用して、Keycloakでエンタープライズアプリケーションを保護しました。私が直面している問題は、残りの Web サービスが呼び出されたときに、現在ログインしているユーザー名を知る必要があることです。Keycloak からログインしているユーザー情報を取得するにはどうすればよいですか?

などを使ってみSecurityContextましWebListenerたが、どれも必要な詳細を教えてくれません。

4

5 に答える 5

31

セキュリティ コンテキストからすべてのユーザー情報を取得します。

例:

public class Greeter {

  @Context
  SecurityContext sc;

  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public String sayHello() {

    // this will set the user id as userName
    String userName = sc.getUserPrincipal().getName();

    if (sc.getUserPrincipal() instanceof KeycloakPrincipal) {
      KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>)  sc.getUserPrincipal();

      // this is how to get the real userName (or rather the login name)
      userName = kp.getKeycloakSecurityContext().getIdToken().getPreferredUsername();
    }

    return "{ message : \"Hello " + userName + "\" }";
}

セキュリティ コンテキストを伝播するには、次の説明に従ってセキュリティ ドメインを設定する必要があります。 JBoss/Wildfly アダプタの設定

于 2015-08-07T05:28:54.830 に答える
20

Web アプリprincipal-attributeのファイルのプロパティを に設定することもできます。keycloak.jsonpreferred_username

于 2016-08-30T11:05:02.307 に答える
1

次の行に standalone.xml を追加する必要があります。

<principal-attribute>preferred_username</principal-attribute>

例:

<subsystem xmlns="urn:jboss:domain:keycloak:1.1">
    <secure-deployment name="war-name.war">
        <realm>realm-name</realm>
        <resource>resource-name</resource>
        <public-client>true</public-client>
        <auth-server-url>https://keycloak-hostname/auth</auth-server-url>
        <ssl-required>EXTERNAL</ssl-required>
        <principal-attribute>preferred_username</principal-attribute>
    </secure-deployment>
</subsystem>
于 2018-05-08T15:38:52.567 に答える