我有一个Spring Boot应用程序,每个控制器上都有OAuth2,但我也想基于访问该方法的用户向控制器内的方法添加基于角色的安全性,但是我无法使其正常工作。有什么建议吗?
我的安全配置:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private static final RequestMatcher PUBLIC_URLS = new OrRequestMatcher(new AntPathRequestMatcher("/public/**"));
private static final RequestMatcher PRIVATE_URLS = new NegatedRequestMatcher(PUBLIC_URLS);
private TokenAuthenticationProvider tokenProvider;
public SecurityConfiguration(TokenAuthenticationProvider tokenAuthenticationProvider) {
this.tokenProvider = tokenAuthenticationProvider;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(tokenProvider);
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().requestMatchers(PUBLIC_URLS);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.exceptionHandling().defaultAuthenticationEntryPointFor(forbiddenEntryPoint(), PRIVATE_URLS).and()
.authenticationProvider(tokenProvider).addFilterBefore(restAuthenticationFilter(), AnonymousAuthenticationFilter.class)
.authorizeRequests().requestMatchers(PRIVATE_URLS).authenticated().
.csrf().disable()
.formLogin().disable()
.httpBasic().disable()
.logout().disable();
}
@Bean
public TokenAuthenticationFiller restAuthenticationFilter() throws Exception {
TokenAuthenticationFiller filler = new TokenAuthenticationFiller(PRIVATE_URLS);
filler.setAuthenticationManager(authenticationManager());
filler.setAuthenticationSuccessHandler(successHandler());
return filler;
}
@Bean
public SimpleUrlAuthenticationSuccessHandler successHandler() {
SimpleUrlAuthenticationSuccessHandler successHandler = new SimpleUrlAuthenticationSuccessHandler();
successHandler.setRedirectStrategy(new NoRedirectStrategy());
return successHandler;
}
@Bean
public FilterRegistrationBean disableAutoRegistration(TokenAuthenticationFiller tokenAuthenticationFiller) {
FilterRegistrationBean registrationBean = new FilterRegistrationBean(tokenAuthenticationFiller);
registrationBean.setEnabled(false);
return registrationBean;
}
@Bean
public AuthenticationEntryPoint forbiddenEntryPoint() {
return new HttpStatusEntryPoint(HttpStatus.FORBIDDEN);
}