【发布时间】:2021-05-03 18:17:11
【问题描述】:
我正在寻找具有以下属性的 spring-security 配置 WebSecurityConfigurerAdapter#configure():
GET /api/v3/ <= REST endpoints only authenticated (k
POST /api/v4/graphql <= My new GraphQL endpoint, allow anonymous but only for POST
POST /api/v4/subscriptions <= GraphQL subscriptions, allow anonymous
GET /playground <= GraphQL playground web app
GET /vendor <= JS and CSS resources for GraphQL playground
“旧”/api/v3 配置在自己的WebSecurityConfigurerAdapter 中:
@Configuration
public class OldApiSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
String basePath = "/api/v3" // old REST api
@Override
protected void configure(HttpSecurity http) throws Exception {
log.info("Configuring HttpWebSecurity for "+ basePath);
http
.authorizeRequests()
.antMatchers(basePath+"/_ping").permitAll() // allow is alive ping
.anyRequest().authenticated() // everything else must be authenticated
.and()
.csrf().disable()
.formLogin().disable()
.httpBasic().disable()
.logout().disable();
}
}
到目前为止效果很好。不,我尝试添加第二个配置器:
@Configuration
@Order(30) // MUST be smaller than 100 to be first!
public class GraphQlSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
String basePath = "/api/v4"; // new GraphQL API
protected void configure(HttpSecurity http) throws Exception {
AndRequestMatcher allowedGraphQlRequests = new AndRequestMatcher(
new RegexRequestMatcher(basePath + "/graphql", HttpMethod.POST.name()),
new RegexRequestMatcher(basePath + "/subscriptions", HttpMethod.GET.name()),
new RegexRequestMatcher(basePath + "/playground", HttpMethod.GET.name()),
new RegexRequestMatcher(basePath + "/vendor", HttpMethod.GET.name())
);
http.requestMatcher(allowedGraphQlRequests) // MUST limit this to only these URLs !
.authorizeRequests()
.antMatchers(basePath + "/graphql").permitAll()
.antMatchers(basePath + "/subscriptions").permitAll()
.antMatchers(basePath + "/playground").permitAll()
.antMatchers(basePath + "/vendor/**").permitAll().and().csrf().disable();
}
}
但现在只允许经过身份验证的请求。到目前为止,我的调试表明 RegexRequestMatchers 被正确评估并匹配给定的路径。
我需要为我的 GraphQL 发布请求禁用 CSRF()。如上所示,这是正确的地方吗?
还是需要这样?
http.requestMatcher(allowedGraphQlRequests) // MUST limit this to only these URLs !
.authorizeRequests()
.antMatchers(basePath + LiquidoUrlPaths.GRAPHQL).permitAll().and().csrf().disable()
.authorizeRequests()
.antMatchers(basePath + LiquidoUrlPaths.SUBSCRIPTIONS).permitAll()
.antMatchers(basePath + LiquidoUrlPaths.PLAYGROUND).permitAll()
.antMatchers(basePath + LiquidoUrlPaths.VENDOR + "/**").permitAll();
我很困惑???? :-( 我如何配置我的 GraphQL API 以允许匿名 POST 请求到 /api/v4/graphql 而没有 CSRF?
【问题讨论】: