我使用的是Spring Boot 2.0。我不知道最好的方法是什么,但这里有一种方法对我有效。我必须将其划分为不同的配置类,第二个配置需要
@订单号
上面的批注。
对于我的特殊情况,我需要一些由HTTP基本身份验证(用户名/密码)保护的管理REST方法,其余的REST方法需要由自定义逻辑保护。
@Configuration
@EnableWebSecurity
public class TestSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll();
// anything that is NOT /admin/**
RequestMatcher requestMatcher = new NegatedRequestMatcher(new AntPathRequestMatcher("/admin/**", "GET"));
// MyCustomFilter is my class that performs custom authentication logic
http.requestMatcher(requestMatcher)
.addFilterAfter(new MyCustomFilter(), BasicAuthenticationFilter.class);
}
@Order(1)
@Configuration
public static class AdminServiceConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//this time anything that IS /admin/**
http.requestMatchers()
.antMatchers("/admin/**").and()
.httpBasic().and()
.authorizeRequests().antMatchers("/admin/**").fullyAuthenticated();
}
@Override
protected void configure(AuthenticationManagerBuilder authBuilder) throws Exception {
authBuilder.inMemoryAuthentication()
.passwordEncoder(NoOpPasswordEncoder.getInstance())
.withUser("username")
.password("password")
.roles("ADMIN");
}
}
}