Spring Boot + Security + Multi HTTP веб-конфигурация
Я пытаюсь сделать пример, используя Spring-Boot с Spring Security. Моя идея состоит в том, чтобы создать веб-приложение, а также предоставить API, я бы хотел, чтобы оба имели безопасность; поэтому мне нужно создать конфигурацию веб-безопасности с несколькими http, однако она не работает.
Я перешел по этой ссылке http://docs.spring.io/spring-security/site/docs/3.2.x/reference/htmlsingle/, но безуспешно. И я получаю эту ошибку
Ошибка создания бина с именем 'webSecurityConfiguration': сбой внедрения зависимостей с автопроводкой; Вложенным исключением является java.lang.IllegalStateException: невозможно применить org.springframework.security.config.annotation.authentication.configurers.provisioning.InMemoryUserDetailsManagerConfigurer к уже построенному объекту.
Я использую следующую конфигурацию:
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
@EnableGlobalAuthentication
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfiguration {
@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("12345").roles("USER").and()
.withUser("admin").password("12345").roles("USER", "ADMIN");
}
@Configuration
@Order(1)
public static class ApiConfigurationAdapter extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**")
.authorizeRequests()
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic();
}
}
@Configuration
@Order(2)
public static class WebConfigurationAdapter extends
WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.and()
.logout().permitAll();
}
}
}
заранее спасибо
3 ответа
После долгих чтений я нашел то, что работает для меня:
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfiguration extends GlobalAuthenticationConfigurerAdapter {
@Resource(name = "customUserDetailsService")
protected CustomUserDetailsService customUserDetailsService;
@Resource
private DataSource dataSource;
@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService);
}
@Configuration
@Order(1)
public static class ApiConfigurationAdapter extends WebSecurityConfigurerAdapter {
@Resource(name = "restUnauthorizedEntryPoint")
private RestUnauthorizedEntryPoint restUnauthorizedEntryPoint;
@Resource(name = "restAccessDeniedHandler")
private RestAccessDeniedHandler restAccessDeniedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
SecurityConfigurer<DefaultSecurityFilterChain, HttpSecurity> securityXAuthConfigurerAdapter = new XAuthTokenConfigurer(
userDetailsServiceBean());
// @formatter:off
http
.antMatcher("/api/**").csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.exceptionHandling()
.authenticationEntryPoint(restUnauthorizedEntryPoint)
.accessDeniedHandler(restAccessDeniedHandler)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/api/authenticate").permitAll()
.anyRequest().hasRole("ADMIN")
.and()
.apply(securityXAuthConfigurerAdapter);
// @formatter:on
}
}
@Configuration
@Order(2)
public static class WebConfigurationAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.and()
.logout().permitAll()
;
// @formatter:on
}
}
}
Я обнаружил, что могу решить эту проблему, пометив свой класс@EnableWebSecurity
после прочтения этой подсказки: https://github.com/spring-projects/spring-data-examples/issues/189
Я тоже столкнулся с той же проблемой. Но я понял это, когда расширил мастер-класс WebSecurityConfiguration из WebSecurityConfigurerAdapter.
Пожалуйста, обратитесь к следующему сообщению stackru, в котором вы можете найти полную конфигурацию.
Spring Security HTTP Basic для RESTFul и FormLogin для веб - Аннотации