我有 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 ?
最佳答案
.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/