Bilal Dekar
Bilal Dekar

Reputation: 3966

How to get Keycloak token in Spring

I have Spring application with Angular frontend, I secured the two sides with Keycloak 11.0.2, how can I get the token information when a request is sent from a frontend, for example I want to access the authenticated user information and attributes in Spring side, because I the returned request depends on the users attributes.

Below is my configuration in spring :

keycloak.auth-server-url=http://localhost:8080/auth
keycloak.realm=myapp
keycloak.resource=myapp-api
keycloak.ssl-required=external
keycloak.bearer-only=true
keycloak.principal-attribute=preferred_username


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http.authorizeRequests().anyRequest().permitAll();
        http.csrf().disable();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
        keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
        auth.authenticationProvider(keycloakAuthenticationProvider);
    }

    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new NullAuthenticatedSessionStrategy();
    }

    @Bean
    public KeycloakSpringBootConfigResolver KeycloakConfigResolver() {
        return new KeycloakSpringBootConfigResolver();
    }
}

Upvotes: 1

Views: 1400

Answers (1)

dreamcrash
dreamcrash

Reputation: 51423

Based upon your question, I think you are referring to the ID token, which you can get (for instance) from the request. Check the following example:

@GetMapping(path = "/student")
public String teen(HttpServletRequest request) throws ServletException {
       KeycloakAuthenticationToken token = (KeycloakAuthenticationToken) request.getUserPrincipal();
       System.out.println("---- ROLES ----");
       token.getAccount().getRoles().forEach(System.out::println);
       Map<String, Object> otherClaims = token.getAccount().getKeycloakSecurityContext().getIdToken().getOtherClaims();

       Enumeration<String> attributeNames = request.getAttributeNames();
       while (attributeNames.hasMoreElements())
            System.out.println(attributeNames.nextElement());

       for(String s : otherClaims.keySet()){
            System.out.println(s);
            System.out.println(otherClaims.get(s).toString());
       }

       System.out.println("------------");
       return "student";
    }

The code above is just an example, but is showcases some on the API functionality.

Upvotes: 2

Related Questions