我有一个简单的 Spring Boot 应用程序,它公开了一个 REST API。 我已使用 @PreAuthorize("hasRole('ROLE_4')") 注释成功配置 spring 安全性以根据其 ROLE 保护其余 API 中的每个方法。
我注意到,如果我根本不放置 @PreAuthorize 注释,框架将允许向任何经过身份验证的用户发出此请求。我想扭转这种行为。因此,如果其中一位程序员忘记添加 @PreAuthorize 注释,对此方法的任何请求都将被自动拒绝。
这是我的配置:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//Disable HTTP Basic authentication
http.httpBasic().disable();
//Add the filters
http.addFilterBefore(new AuthenticationFilter(authenticationManager()), BasicAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(securityServiceAuthenticationProvider());
}
@Bean
public AuthenticationProvider securityServiceAuthenticationProvider() {
return new SecurityServiceAuthenticationProvider();
}
}
谢谢 盖伊胡达拉
最佳答案
您可以使用 MethodSecurityInterceptor;示例 XML 配置为 here .该示例将安全性应用于单个 bean,但表达式非常灵活,您可以保护例如名称以“Controller”结尾的任何类的所有公共(public)成员。我以前用过类似的XML配置,但是我没有用Java配置做过;但我想您可以在 Java 配置中做同样的事情。
关于java - Spring 安全 : How to reject a request by default if no @PreAuthorize was specified,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39231402/