標準のwildflyベースのKeycloakアダプターを使用して、Keycloakでエンタープライズアプリケーションを保護しました。私が直面している問題は、残りの Web サービスが呼び出されたときに、現在ログインしているユーザー名を知る必要があることです。Keycloak からログインしているユーザー情報を取得するにはどうすればよいですか?
などを使ってみSecurityContext
ましWebListener
たが、どれも必要な詳細を教えてくれません。
セキュリティ コンテキストからすべてのユーザー情報を取得します。
例:
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 アダプタの設定
Web アプリprincipal-attribute
のファイルのプロパティを に設定することもできます。keycloak.json
preferred_username
次の行に 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>