Advertisement
ILyaCyclone

KeycloakWebSecurityConfigurerAdapter

May 3rd, 2021
1,072
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.28 KB | None | 0 0
  1. package cyclone.keycloak.adapterclient;
  2.  
  3. import org.keycloak.adapters.KeycloakConfigResolver;
  4. import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
  5. import org.keycloak.adapters.springsecurity.KeycloakConfiguration;
  6. import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
  7. import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.context.annotation.Bean;
  10. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  11. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
  12. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  13. import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
  14. import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
  15. import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
  16.  
  17. @KeycloakConfiguration
  18. @EnableGlobalMethodSecurity(prePostEnabled = true)
  19. public class WebSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
  20.  
  21.     @Override
  22.     protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
  23.         return new NullAuthenticatedSessionStrategy();
  24.     }
  25.  
  26.     @Autowired
  27.     public void configureGlobal(AuthenticationManagerBuilder authManagerBuilder) {
  28.         KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
  29.         // adding proper authority mapper for prefixing role with "ROLE_"
  30.         keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
  31.         authManagerBuilder.authenticationProvider(keycloakAuthenticationProvider);
  32.     }
  33.  
  34.     @Bean
  35.     public KeycloakConfigResolver keycloakConfigResolver() {
  36.         return new KeycloakSpringBootConfigResolver();
  37.     }
  38.  
  39.     @Override
  40.     protected void configure(HttpSecurity http) throws Exception {
  41.         super.configure(http);
  42.         http
  43.                 .authorizeRequests()
  44.                 .antMatchers("/api/anonymous/**").permitAll()
  45.                 .anyRequest().fullyAuthenticated();
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement