title: Spring Keycloak: Get User ID
body: <p>I have developed a Spring Boot Webservice and use Keycloak for Access Management. 
  The website stores some userdata in a database. I try to connect these data with the user logged in. </p>
  
  <p>At the moment I store the username with the data. But I like to store the user id instead the username. How can I do that? </p>
  
  <p>I try to get SecurityContext by this: </p>
  
  <pre><code>@Bean
  @Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
  public KeycloakSecurityContext getKeycloakSecurityContext() {
      return ((KeycloakPrincipal&lt;KeycloakSecurityContext&gt;) getRequest().getUserPrincipal()).getKeycloakSecurityContext();
  }
  </code></pre>
  
  <p>But I get an error: </p>
  
  <pre><code>There was an unexpected error (type=Internal Server Error, status=500).
  Error creating bean with name 'scopedTarget.getKeycloakSecurityContext'
  defined in com.SiteApplication: Bean instantiation via factory method
  failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate [org.keycloak.KeycloakSecurityContext]: Factory method
  'getKeycloakSecurityContext' threw exception; nested exception is
  java.lang.ClassCastException:
  org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken
  cannot be cast to org.keycloak.KeycloakPrincipal
  </code></pre>
  
  <p>Is this the right way? What is missing? </p>
  
  <p>Thank you! </p>