title: How can I read all users using keycloak and spring?
body: <p>I'm using <code>keycloak 3.4</code> and <code>spring boot</code> to develop a web app.
  I'm using the Active Directory as User Federation to retrieve all users information.</p>
  <p>But to use those information inside my web app I think I have to save them inside the &quot;local-webapp&quot; database.</p>
  <p>So after the users are logged, how can I save them inside my database?</p>
  <p>I'm thinking about a <strong>scenario</strong> like: &quot;I have an object A which it refers to the user B, so I have to put a relation between them. So I add a foreign key.&quot;</p>
  <p>In that case I need to have the user on my DB. no?</p>
  <p><strong>EDIT</strong></p>
  <p>To avoid to get save all users on my DB I'm trying to use the Administrator API, so I added the following code inside a controller.</p>
  <p>I also created another client called <code>Test</code> to get all users, in this way I can use <code>client-id</code> and <code>client-secret.</code> Or is there a way to use the <code>JWT</code> to use the admin API?</p>
  <p><strong>The client:</strong></p>
  <pre><code>     Keycloak keycloak2 = KeycloakBuilder.builder()
                           .serverUrl(&quot;http://localhost:8080/auth/admin/realms/MYREALM/users&quot;)
                           .realm(&quot;MYREALMM&quot;)
                           .username(&quot;u.user&quot;)
                           .password(&quot;password&quot;)
                           .clientId(&quot;Test&quot;)
                           .clientSecret(&quot;cade3034-6ee1-4b18-8627-2df9a315cf3d&quot;)
                           .resteasyClient(new ResteasyClientBuilder().connectionPoolSize(20).build())
                           .build();
  
   RealmRepresentation realm2 = keycloak2.realm(&quot;MYREALMM&quot;).toRepresentation();
  </code></pre>
  <p>the error is:</p>
  <pre><code>2018-02-05 12:33:06.638 ERROR 16975 --- [nio-8080-exec-7] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.Error: Unresolved compilation problem: 
      The method realm(String) is undefined for the type AccessTokenResponse
  ] with root cause
  
  java.lang.Error: Unresolved compilation problem: 
      The method realm(String) is undefined for the type AccessTokenResponse
  </code></pre>
  <p>Where am I doing wrong?</p>
  <p><strong>EDIT 2</strong></p>
  <p>I also tried this:</p>
  <pre><code>@Autowired
  private HttpServletRequest request;
  
  public ResponseEntity listUsers() {
      KeycloakAuthenticationToken token = (KeycloakAuthenticationToken) request.getUserPrincipal();        
      KeycloakPrincipal principal=(KeycloakPrincipal)token.getPrincipal();
      KeycloakSecurityContext session = principal.getKeycloakSecurityContext();
          
      Keycloak keycloak = KeycloakBuilder.builder()
                                          .serverUrl(&quot;http://localhost:8080/auth&quot;)
                                          .realm(&quot;MYREALMM&quot;)
                                          .authorization(session.getToken().getAuthorization().toString())
                                          .resteasyClient(new ResteasyClientBuilder().connectionPoolSize(20).build())
                                          .build();
      
      RealmResource r = keycloak.realm(&quot;MYREALMM&quot;);
      List&lt;org.keycloak.representations.idm.UserRepresentation&gt; list = keycloak.realm(&quot;MYREALMM&quot;).users().list();
      return ResponseEntity.ok(list);
  </code></pre>
  <p>but the authorization is always <code>null</code>.
  Why?</p>
  <p><strong>EDIT 3</strong>
  Following you can find my spring security config:</p>
  <pre><code>    @Configuration
  @EnableWebSecurity
  @EnableGlobalMethodSecurity(prePostEnabled=true)
  @ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
  @KeycloakConfiguration
  public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
      
      @Override
      protected void configure(HttpSecurity http) throws Exception {
           super.configure(http);
       
          http.httpBasic().disable();
          http
          .csrf().disable()
          .authorizeRequests()
              .antMatchers(&quot;/webjars/**&quot;).permitAll()
              .antMatchers(&quot;/resources/**&quot;).permitAll()
              .anyRequest().authenticated()
          .and()
          .logout()
              .logoutUrl(&quot;/logout&quot;)
              .logoutRequestMatcher(new AntPathRequestMatcher(&quot;/logout&quot;, &quot;GET&quot;))
              .permitAll()
              .logoutSuccessUrl(&quot;/&quot;)
              .invalidateHttpSession(true);
      }
  
        @Autowired
          public KeycloakClientRequestFactory keycloakClientRequestFactory;
  
          @Bean
          public KeycloakRestTemplate keycloakRestTemplate() {
              return new KeycloakRestTemplate(keycloakClientRequestFactory);
          }
          
      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder auth) {
    
          KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
          SimpleAuthorityMapper simpleAuthorityMapper = new SimpleAuthorityMapper();
          simpleAuthorityMapper.setPrefix(&quot;ROLE_&quot;);
          simpleAuthorityMapper.setConvertToUpperCase(true);
          keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(simpleAuthorityMapper);
          auth.authenticationProvider(keycloakAuthenticationProvider);
      }
   
      @Bean
      public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
          return new KeycloakSpringBootConfigResolver();
      }
   
      @Bean
      @Override
      protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
          return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
      }
      
      @Override
      public void configure(WebSecurity web) throws Exception {
          web
             .ignoring()
             .antMatchers(&quot;/resources/**&quot;, &quot;/static/**&quot;, &quot;/css/**&quot;, &quot;/js/**&quot;, &quot;/images/**&quot;, &quot;/webjars/**&quot;);
      }
      
       @Bean
       @Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
       public AccessToken accessToken() {
           HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
           return ((KeycloakSecurityContext) ((KeycloakAuthenticationToken) request.getUserPrincipal()).getCredentials()).getToken();
       }
       
  }
  </code></pre>
  <p><strong>EDIT 4</strong></p>
  <p>These are the properties inside the <code>applicatoin.properties</code></p>
  <pre><code>#######################################
  #             KEYCLOAK                #
  #######################################
  
  keycloak.auth-server-url=http://localhost:8181/auth
  keycloak.realm=My Realm 
  keycloak.ssl-required=external
  keycloak.resource=AuthServer
  keycloak.credentials.jwt.client-key-password=keystorePwd
  keycloak.credentials.jwt.client-keystore-file=keystore.jks
  keycloak.credentials.jwt.client-keystore-password=keystorePwd
  keycloak.credentials.jwt.alias=AuthServer
  keycloak.credentials.jwt.token-expiration=10
  keycloak.credentials.jwt.client-keystore-type=JKS
  keycloak.use-resource-role-mappings=true
  keycloak.confidential-port=0
  keycloak.principal-attribute=preferred_username
  </code></pre>
  <p>EDIT 5.</p>
  <p>This is my keycloak config:
  <a href="https://i.stack.imgur.com/y9E4e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y9E4e.png" alt="enter image description here" /></a></p>
  <p>the user that I'm using to login with view user permission:
  <a href="https://i.stack.imgur.com/FewNa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FewNa.png" alt="enter image description here" /></a></p>
  <p><strong>EDIT 6</strong></p>
  <p>This the log form keycloak after enabling logging:</p>
  <pre><code>2018-02-12 08:31:00.274 3DEBUG 5802 --- [nio-8080-exec-1] o.k.adapters.PreAuthActionsHandler       : adminRequest http://localhost:8080/utente/prova4
  2018-02-12 08:31:00.274 3DEBUG 5802 --- [nio-8080-exec-1] .k.a.t.AbstractAuthenticatedActionsValve : AuthenticatedActionsValve.invoke /utente/prova4
  2018-02-12 08:31:00.274 3DEBUG 5802 --- [nio-8080-exec-1] o.k.a.AuthenticatedActionsHandler        : AuthenticatedActionsValve.invoke http://localhost:8080/utente/prova4
  2018-02-12 08:31:00.274 3DEBUG 5802 --- [nio-8080-exec-1] o.k.a.AuthenticatedActionsHandler        : Policy enforcement is disabled.
  2018-02-12 08:31:00.275 3DEBUG 5802 --- [nio-8080-exec-1] o.k.adapters.PreAuthActionsHandler       : adminRequest http://localhost:8080/utente/prova4
  2018-02-12 08:31:00.275 3DEBUG 5802 --- [nio-8080-exec-1] o.k.a.AuthenticatedActionsHandler        : AuthenticatedActionsValve.invoke http://localhost:8080/utente/prova4
  2018-02-12 08:31:00.275 3DEBUG 5802 --- [nio-8080-exec-1] o.k.a.AuthenticatedActionsHandler        : Policy enforcement is disabled.
  2018-02-12 08:31:00.276 3DEBUG 5802 --- [nio-8080-exec-1] o.k.adapters.PreAuthActionsHandler       : adminRequest http://localhost:8080/utente/prova4
  2018-02-12 08:31:00.276 3DEBUG 5802 --- [nio-8080-exec-1] o.k.a.AuthenticatedActionsHandler        : AuthenticatedActionsValve.invoke http://localhost:8080/utente/prova4
  2018-02-12 08:31:00.276 3DEBUG 5802 --- [nio-8080-exec-1] o.k.a.AuthenticatedActionsHandler        : Policy enforcement is disabled.
  2018-02-12 08:31:10.580 3DEBUG 5802 --- [nio-8080-exec-1] o.k.a.s.client.KeycloakRestTemplate      : Created GET request for &quot;http://localhost:8181/auth/admin/realms/My%20Realm%20name/users&quot;
  2018-02-12 08:31:10.580 3DEBUG 5802 --- [nio-8080-exec-1] o.k.a.s.client.KeycloakRestTemplate      : Setting request Accept header to [application/json, application/*+json]
  2018-02-12 08:31:10.592 3DEBUG 5802 --- [nio-8080-exec-1] o.k.a.s.client.KeycloakRestTemplate      : GET request for &quot;http://localhost:8181/auth/admin/realms/My%20Realm%20name/users&quot; resulted in 401 (Unauthorized); invoking error handler
  2018-02-12 08:31:10.595 ERROR 5802 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException: 401 Unauthorized] with root cause
  
  org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
      at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:85) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
      at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:707) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
  </code></pre>