Конфигурация HttpSecurity не работает с адаптером Keycloak в Spring

Полный код: https://github.com/czetsuya/Spring-Keycloak-with-REST-API

Я пытаюсь реализовать REST API в Spring, защищенный Keycloak (4.8.1), с клиентом только для носителя.

Проблема: configure (HttpSecurity http) не соблюдается, и пока пользователь аутентифицирован, конечные точки REST доступны.

Например, с .antMatchers ("/ admin *"). HasRole ("ADMIN") / admin должен быть доступен только пользователю с ролью ADMIN, но я смог получить доступ с помощью роли USER.

Я также попытался установить ограничения безопасности в application.yml (но не помогло):

  security-constraints:
  - auth-roles:
    - ADMIN
  - security-collections:
    - name: admin
    - patterns:
      - /admin*

Использование @EnableGlobalMethodSecurity в сочетании с @PreAuthorize ("hasRole ('ADMIN')") может помочь, но разве нет другого пути?

Вот application.xml.

keycloak:
  enabled: true
  realm: dev
  auth-server-url: http://localhost:8083/auth
  ssl-required: external
  resource: dev-api
  bearer-only: true
  confidential-port: 0
  use-resource-role-mappings: false
  principal-attribute: preferred_username

Вот зависимости от pom:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.keycloak</groupId>
        <artifactId>keycloak-spring-boot-starter</artifactId>
    </dependency>
    .....

И часть класса SecurityConfig:

@KeycloakConfiguration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {

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

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

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

    @Autowired
    public KeycloakClientRequestFactory keycloakClientRequestFactory;

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public KeycloakRestTemplate keycloakRestTemplate() {
        return new KeycloakRestTemplate(keycloakClientRequestFactory);
    }

    /**
     * Secure appropriate endpoints
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http.authorizeRequests() //
                .antMatchers("/users*").hasRole("USER") //
                .antMatchers("/admin*").hasRole("ADMIN") //
                .anyRequest().authenticated() //
                .and().csrf().disable() //
        ;
    }

После включения подробного журнала. Я обнаружил, что применяются ограничения безопасности, определенные в application.yml, но не ограничения, определенные в классе java.

Теперь вопрос в том, как использовать ограничения java вместо определенного application.yml.


person czetsuya    schedule 27.12.2018    source источник


Ответы (1)


Проблема заключалась в неправильной конфигурации yml. Вот правильная версия:

security-constraints:
    - auth-roles:
      - User
      security-collections:
      - name: unsecured
        patterns:
        - /users
    - auth-roles: 
      - Admin
      security-collections:
      - name: secured
        patterns:
        - /admin

Обратите внимание, что когда определен KeycloakSpringBootConfigResolver, также будет вызвана конфигурация (httpSecurity).

Включение журнала ниже в application.yml покажет нам проверку ограничений безопасности:

logging:
  level:
    org.apache.catalina: DEBUG

Вот более подробное объяснение с кодом: http://czetsuya-tech.blogspot.com/2018/12/secure-spring-boot-rest-project-with.html

person czetsuya    schedule 01.01.2019