简体   繁体   English

如何通过Java API在Keycloak中设置自定义用户属性

[英]How to set Custom User Property in keycloak from java api

I am using keycloak for authentication in my spring application, how can I set some attribute for a user. 我在spring应用程序中使用keycloak进行身份验证,如何为用户设置一些属性。 I have already added a custom mapper on admin console. 我已经在管理控制台上添加了自定义映射器。

Please have a look below attached screen shot,in user section there is the tab where you can set the attributes 请在所附的屏幕截图下方看一下,在用户部分,有一个可以设置属性的选项卡

在此处输入图片说明

Now question will be how you will access those user attributes through code? 现在的问题是如何通过代码访问那些用户属性?

So here is the code which can be use to access user attributes . 因此,这里是可用于访问用户属性的代码。

HttpServletRequest httpRequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        KeycloakSecurityContext securityContext = (KeycloakSecurityContext) httpRequest.getAttribute(KeycloakSecurityContext.class.getName());
          AccessToken accessToken = securityContext.getToken();
          if(null != accessToken ){
          Map<String, Object> otherClaims = accessToken.getOtherClaims() ;     
          tgtToken = securityContext.getTokenString();
          String firstUserAtt = otherClaims.get("First_User_Attribute").toString();
          String secondUserAtt = otherClaims.get("Second_User_Attribute").toString();
}

Note - First_User_Attribute , Second_User_Attribute are the key you declare in the keycloak's user attribute section. 注意First_User_AttributeSecond_User_Attribute是您在密钥斗篷的用户属性部分中声明的密钥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM