【问题标题】:Is it possible to secured only controllers marked with Spring @Secured annotation是否可以仅保护标有 Spring @Secured 注释的控制器
【发布时间】:2018-01-10 21:10:45
【问题描述】:

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

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

控制器:

@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();
    }
}

编辑:

我想要保护 100 个控制器中的 50 个, 但不想手动在配置中编写它们

【问题讨论】:

  • 如果您只有一个受保护的控制器(使用@Secured),则可以允许所有路径(anyRequest().permitAll())。

标签: java spring spring-security


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2015-01-28
    • 1970-01-01
    • 2016-01-20
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    • 2012-10-05
    • 2015-09-04
    • 2011-05-03
    相关资源
    最近更新 更多