gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:59:25 27 4
gpt4 key购买 nike

我有 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/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com