I have tried the Spring Security Kotlin DSL feature introduced in Spring Security 5.3.
The example is here.
Currently, I have to define a WebSecurityConfigurerAdapter like this.
bean<WebSecurityConfigurerAdapter> {
val config = object : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity?) {
http {
csrf { disable() }
httpBasic { }
securityMatcher("/**")
authorizeRequests {
authorize("/auth/**", authenticated)
authorize(AntPathRequestMatcher("/posts/**", HttpMethod.GET.name), permitAll)
authorize(AntPathRequestMatcher("/posts/**", HttpMethod.DELETE.name), "hasRole('ADMIN')")
authorize("/posts/**", authenticated)
authorize(anyRequest, permitAll)
}
}
}
}
config
}
The RouterFunctionDSL can be nested in BeanDefinitionDSL directly.
bean {
val postHandler = ref<PostHandler>()
val userInfoHandler = ref<UserInfoHandler>()
router {
"posts".nest {
GET("", postHandler::all)
GET("count", postHandler::count)
GET("{id}", postHandler::get)
POST("", postHandler::create)
PUT("{id}", postHandler::update)
PATCH("{id}", postHandler::updateStatus)
DELETE("{id}", postHandler::delete)
//comments
"{id}/comments".nest {
GET("count", postHandler::countCommentsOfPost)
GET("", postHandler::getCommentsOfPost)
POST("", postHandler::createComment)
}
}
//get user info
"/auth".nest {
GET("/user", userInfoHandler::userInfo)
GET("/logout", userInfoHandler::logout)
}
}
}
Is it possible to add another DSL to make the security config nested in BeanDefinitionDSL, like the router config? eg.
bean{
security{
http{}
websocket{}
rsocket{}
}
}
Comment From: eleftherias
@hantsy In Spring Security 5.4.0, we added the ability to configure HttpSecurity by exposing a bean, instead of extending WebSecurityConfigurerAdapter (see #8804).
This means you can nest the SecurityFilterChain bean in the BeanDefinitionDsl
val beans = beans {
bean {
val httpSecurity = ref<HttpSecurity>()
httpSecurity {
authorizeRequests {
authorize("/css/**", permitAll)
authorize("/user/**", hasAuthority("ROLE_USER"))
}
formLogin {
loginPage = "/log-in"
}
}
httpSecurity.build()
}
}
If you're using Spring Boot, make sure to use the latest 2.4.0 milestone (2.4.0-M3 at this moment).
Comment From: eleftherias
I'm going to close this issue, if you run into any problems feel free to continue the conversation here.