spring - 用于 API 安全性的 AntMatcher 和 contextPath

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

我有 Spring 启动应用程序。我已配置 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我知道

The pattern must not contain the context path



确实,从:
.antMatchers("/api/**" ).authenticated();

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

工作正常。但问题是:在这个用例中是否可以使用上下文路径,而不是使用 /** ?我可以重复 .antMatchers()对于每个 Controller (或使用 /** ),但也许有一种方法可以使用 context-path ?

最佳答案

  • 将属性注入(inject)变量并在代码中使用它
  • 我还展示了恕我直言,用 lambda 编写 conf 的更好方式,您不需要使用“.and()”,并且可以更好地看到作用域块。
  • .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());
    
    

    关于spring - 用于 API 安全性的 AntMatcher 和 contextPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53987484/

    相关文章:

    JavaConfig : The type javax. servlet.ServletContext 和 javax.servlet.ServletException 无法解析

    hibernate - 删除未完成

    java - Mongo 模板在 Spring.Mongodb 中按日期间隔聚合

    java - 如何在Thymeleaf `sec:authorize`属性中使用Spring EL表达式

    java - 无法使用 Spring RestTemplate 将 MultiPartFile 混合的 POST 参数发送到 Rest 服务

    java - 如何在 Spring 属性中扩展通配符?

    java - 在 Spring Boot MongoDB 中查找重复条目?

    spring security 没有找到 WebApplicationContext

    java - 在 Weblogic 12c 上部署 Spring Security SAML 扩展时出现问题

    spring-security - 尝试使用 session 管理时出错