因此,我的配置适配器中包含以下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
)的冗余permitAll HTTP GET
(在Java代码上,它使用了接受多个模式的antMatchers)吗?
答案 0 :(得分:1)
您的Kotlin配置与您共享的Java配置不同。
首先,CORS配置
http
.cors()
.and()
// ...
以下是等效的Kotlin配置,因为您是启用CORS而不是禁用它。
http {
cors { }
}
第二,会话管理配置
http
// ...
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
下面是等效的Kotlin配置,您要在其中分配SessionCreationPolicy。
http {
sessionManagement {
sessionCreationPolicy = SessionCreationPolicy.STATELESS
}
}
关于addFilter
方法,在Javadoc中声明
添加必须是安全性框架内提供的过滤器的实例或扩展该过滤器之一的过滤器。
如果您的自定义过滤器BasicJwtAuthenticationFilter
是BasicAuthenticationFilter
的实例,则Kotlin配置正确。
将所有这些加在一起,您将获得以下Kotlin配置
http {
cors { }
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 = SessionCreationPolicy.STATELESS
}
}