I am trying to fetch a custom attribute (phone_number) in the form of a claim from Keycloak. I am following the steps given here. Below are attached screenprints of the steps I have executed.
- Adding attribute to user
- Protocol mapper
I am now trying to access this attribute in a filter as follows.
public class FilterTest extends OncePerRequestFilter {
public static final String PHONE_NUMBER = "phone_number";
public FilterTest() {
}
@Override
protected void doFilterInternal(
final HttpServletRequest request,
final HttpServletResponse response,
final FilterChain filterChain) throws ServletException, IOException {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if( !AnonymousAuthenticationToken.class.isAssignableFrom(authentication.getClass()) ){
Principal principal = (Principal) authentication.getPrincipal();
if (principal instanceof KeycloakPrincipal) {
KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>) principal;
AccessToken token = kp.getKeycloakSecurityContext().getToken();
Map<String, Object> otherClaims = token.getOtherClaims();
System.out.println("Phone number => "+otherClaims.get(PHONE_NUMBER); // null pointer
}
}
filterChain.doFilter(request, response);
}
}
Additional things that I have tried.
- Clear the realm cache.
- Add the built-in phone number protocol mapper.
The above two steps also didn't yield any results for me.
I am not sure what I am missing here. Any help is appreciated.