Как активировать / деактивировать Spring Security через Профили - PullRequest
1 голос
/ 12 марта 2020

У меня есть два экземпляра Spring WebSecurityConfigurerAdapter в моем проекте.

Один разрешает все, другой активирует UserDigest.

Конфигурация без контроля

@Configuration
@EnableWebSecurity
@Profile("secoff")
public class WebSecurityConfigSecOff extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.anonymous().and().csrf().disable();
    }
}

Конфигурация с UserDigest

@Configuration
@EnableWebSecurity
@Profile("secon")
public class WebSecurityConfigSecOn extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.addFilter(digestAuthenticationFilter())
            .exceptionHandling().authenticationEntryPoint(digestEntryPoint())
            .and()
            .httpBasic()
            .and()
            .authorizeRequests()
            .antMatchers( "/services/ESI/*").hasAnyRole("USER")
            .anyRequest().authenticated()
            .and()
            .csrf().disable();

}

Эти два класса также требуют, чтобы это было определено ...

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}

Я бы ожидал, что смогу запустить систему с ...

-Dspring.profiles.active=secon

И защита будет включена.

Это не тот случай, хотя он не запускается и выдает ошибку

NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' available

Он также не срабатывает точка останова любой из двух методов 'configure (HttpSecurity http)'.

Похоже, что ни один профиль не запущен. Если я удаляю аннотацию @profile, она нормально запускается при включенной или выключенной защите.

Может кто-нибудь предложить решение?

Примечание: JDK 1.8, Spring 4.3.7-RELEASE

1 Ответ

0 голосов
/ 19 марта 2020

Причиной этой ошибки было то, что tomcat setEnv.bat имеет этот набор ...

spring.profiles.active=serverMode

Это значение переопределяет то, что я устанавливал в Intellij как параметр -D. Следовательно, мой профиль не был активным.

Другой способ решить эту проблему - перейти от профиля к аннотациям @value ...

@Value("${securityDisabled:false}")
private boolean securityDisabled;

@Override
protected void configure(HttpSecurity http) throws Exception {
    if (securityDisabled)
    {
        http.anonymous().and().csrf().disable();
    }else {
        http.addFilter(digestAuthenticationFilter())
                .exceptionHandling().authenticationEntryPoint(digestEntryPoint())
                .and()
                .httpBasic()
                .and()
                .authorizeRequests()
                .antMatchers( "/services/ESI/*").hasAnyRole("USER")
                .anyRequest().authenticated()
                .and()
                .csrf().disable();
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...