是否可以仅保护标有 Spring @Secured注释的控制器



>我有几个控制器,只想保护其中一个, 花一些时间,但还没有找到合适的解决方案。

如何通过配置来做到这一点?

控制器:

@RestController
@RequestMapping("/somepath")
public class UnsecController {
// code here
}
@Secured("ROLE_CUSTOM")
@RestController
@RequestMapping("/somepath2")
public class SecController {
// code here
}

配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/js/**", "/css/**", "/fonts/**", "/static", "/swagger-ui.html");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.antMatcher("/**")
.addFilterBefore(authFilter(), BasicAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/health").permitAll()
.anyRequest().authenticated()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Bean
public MacaroonsAuthFilter authFilter() {
return new MacaroonsAuthFilter();
}
}

编辑:

我有 50 个控制器,其中 100 个我想要保护, 但不想手动将它们写入配置

控制器通过配置WebSecurityConfigurerAdapter来保护。如果您只想保护一个控制器方法,则需要以这种方式配置 HttpSecurity,使其仅匹配此路径。所有其他方法均排除在安全性之外。内容如下:

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/somepath").hasRole("CUSTOM")
.anyRequest().permitAll();
} 

@Secured注释通常用于服务方法,而不是控制器。

最新更新