首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >API安全的AntMatcher和contextPath

API安全的AntMatcher和contextPath
EN

Stack Overflow用户
提问于 2018-12-31 12:22:29
回答 1查看 2.9K关注 0票数 4

我有弹簧引导申请。我已经配置了OAuth2 -授权服务器和资源服务器(分离的)。在资源服务器(application.properties)中,我有:

代码语言:javascript
复制
server.servlet.context-path=/api

以及:

代码语言:javascript
复制
@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实际上根本没有安全。多亏了医生和@dur's answer我知道

模式不能包含上下文路径。

实际上,从以下几个方面发生了变化:

代码语言:javascript
复制
.antMatchers("/api/**" ).authenticated();

至:

代码语言:javascript
复制
.antMatchers("/**" ).authenticated();

效果很好。但问题是:在这个用例中是否可以使用上下文路径,而不是使用/**?我可以对每个控制器重复.antMatchers() (或者使用/**),但是也许有一种方法可以使用上下文路径?

EN

回答 1

Stack Overflow用户

发布于 2021-10-08 17:04:46

  1. 将属性注入变量并在代码中使用该属性
  2. 我还演示了IMHO更好的用lambda编写conf的方法,在这里您不需要使用".and()“,您可以更好地看到作用域块。
  3. .requestMatchers().and()什么也不做,所以您可以删除它。这在lambda表示法中也更为明显:.requestMatchers(matchers -> matchers)
代码语言:javascript
复制
@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()
            );
    }
}

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

代码语言:javascript
复制
 http. 
    .authorizeRequests()
    .antMatchers(contextPath + "/actuator/**", "/api-docs/**")
    .permitAll()
    .antMatchers(contextPath + "/**" )
    .authenticated()
    .and());
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53987484

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档