【问题标题】:AntMatcher and contextPath for API security用于 API 安全的 AntMatcher 和 contextPath
【发布时间】:2019-05-27 23:42:56
【问题描述】:

我有弹簧启动应用程序。我已经配置了OAuth2 - 授权和资源服务器(分开)。在资源服务器 (application.properties) 我有:

server.servlet.context-path=/api

还有:

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    (...)

    @Override
    public void configure(HttpSecurity http) throws Exception {
                http
                .requestMatchers()
                .and()
                .authorizeRequests()
                .antMatchers("/actuator/**", "/api-docs/**").permitAll()
                .antMatchers("/api/**" ).authenticated();
    }
}

问题在于,api 实际上根本不安全。感谢 doc 和 @dur's answer 我知道

模式不能包含上下文路径

确实,从:

.antMatchers("/api/**" ).authenticated();

到:

.antMatchers("/**" ).authenticated();

工作正常。但问题是:在这个用例中是否可以使用上下文路径,而不是使用 /** ?我可以为每个控制器重复.antMatchers()(或使用/**),但也许有办法使用上下文路径?

【问题讨论】:

  • 2.0.5.RELEASE
  • 为什么需要上下文路径?为什么你认为它更好?但是,您始终可以实现自己的 RequestMatcher。
  • 我认为当你使用特定的上下文/api/** 比使用/** 时,它更具可读性。这让我觉得我没有意外影响/api/** 之外的东西。第二个原因可能是我有多个上下文并希望对每个上下文应用不同的安全逻辑。

标签: spring spring-boot spring-security spring-oauth2


【解决方案1】:
  1. 将属性注入变量并在代码中使用
  2. 恕我直言,我还展示了使用 lambda 编写 conf 的更好方法,您不需要使用“.and()”,并且可以更好地查看范围块。
  3. 空的.requestMatchers().and() 不执行任何操作,因此您可以将其删除。 这在 lambda 表示法中也更明显: .requestMatchers(matchers -> matchers)
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    (...)
    @Value("${server.servlet.context-path:''}")
    private String contextPath; // <<<< I am the path !

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests(authorize -> authorize 
                .antMatchers(contextPath + "/actuator/**", "/api-docs/**").permitAll()
                .antMatchers(contextPath + "/**" ).authenticated()
            );
    }
}

但如果你真的想,你也可以用旧的方式编写代码。 它对使用变量没有影响。 :

 http. 
    .authorizeRequests()
    .antMatchers(contextPath + "/actuator/**", "/api-docs/**")
    .permitAll()
    .antMatchers(contextPath + "/**" )
    .authenticated()
    .and());

【讨论】:

    猜你喜欢
    • 2018-04-28
    • 2018-09-28
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 2018-11-05
    • 2012-10-09
    • 1970-01-01
    相关资源
    最近更新 更多