【发布时间】:2020-12-23 08:19:42
【问题描述】:
所以,我的配置器适配器中有这个 java 代码:
http.cors().and().csrf().disable()
.authorizeRequests().antMatchers(HttpMethod.POST, Constants.CREATE_USER_URL).permitAll()
.and().authorizeRequests().antMatchers(HttpMethod.GET, "/v2/api-docs", "/swagger-resources/**", "/swagger-ui/**", "/swagger-ui.html**", "/webjars/**", "favicon.ico").permitAll().anyRequest().authenticated()
.and().addFilter(new JwtAuthenticationFilter(authenticationManager())).addFilter(new BasicJwtAuthenticationFilter(authenticationManager()))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
我尝试使用新的 Kotlin DSL:
http {
cors { disable() }
csrf { disable() }
authorizeRequests {
authorize(AntPathRequestMatcher(createUserUrl, HttpMethod.POST.name), permitAll)
authorize(AntPathRequestMatcher("favicon.ico", HttpMethod.GET.name), permitAll)
authorize(AntPathRequestMatcher("/v2/api-docs", HttpMethod.GET.name), permitAll)
authorize(AntPathRequestMatcher("/swagger-resources/**", HttpMethod.GET.name), permitAll)
authorize(AntPathRequestMatcher("/swagger-ui/**", HttpMethod.GET.name), permitAll)
authorize(AntPathRequestMatcher("/webjars/**", HttpMethod.GET.name), permitAll)
authorize(anyRequest, authenticated)
}
addFilterAt(JwtAuthenticationFilter(authenticationManager()), AuthenticationFilter::class.java)
addFilterAt(BasicJwtAuthenticationFilter(authenticationManager()), BasicAuthenticationFilter::class.java)
sessionManagement { SessionCreationPolicy.STATELESS }
}
这个 kotlin dsl 是否具有与 java 代码相同的功能? kotlin dsl没有addFilter吗?
我可以减少冗余的authorize(在 Java 代码上,它使用接受多种模式的 antMatchers)具有相似代码 (permitAll HTTP GET)??
【问题讨论】:
-
其他选项是使用
authorize(EndpointRequest.to("/a", "/b", "/c"), permitAll),虽然我不认为您可以指定允许的确切HTTP方法,因此它允许每种方法。 -
@kdev 我尝试在 kotlin dsl 中使用 for 循环。这种方法有什么问题吗?它编译并运行正常,但没有正确测试。
-
看不出有什么问题。您可以在 dsl 上创建扩展方法,并将其称为相同的
authorize,它接受:HTTP 方法和可变参数字符串端点作为参数,并在方法内部迭代并注册它们
标签: java spring-boot kotlin spring-security