The Kotlin DSL to configure HTTP security doesn't work as shown in the documentation.
The following example doesn't compile:
package com.example.demo
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.web.server.ServerHttpSecurity.http
import org.springframework.security.web.SecurityFilterChain
@Configuration
@EnableWebSecurity
class SecurityConfiguration {
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeRequests {
authorize(anyRequest, authenticated)
}
formLogin { }
httpBasic { }
}
return http.build()
}
}
The compiler reports these errors:
e: C:\..\SecurityConfig.kt: (16, 14): Too many arguments for public open fun http(): ServerHttpSecurity! defined in org.springframework.security.config.web.server.ServerHttpSecurity
e: C:\..\SecurityConfig.kt: (17, 13): Unresolved reference: authorizeRequests
e: C:\..\SecurityConfig.kt: (18, 17): Unresolved reference: authorize
e: C:\..\SecurityConfig.kt: (18, 27): Unresolved reference: anyRequest
e: C:\..\SecurityConfig.kt: (18, 39): Unresolved reference: authenticated
e: C:\..\SecurityConfig.kt: (20, 13): Unresolved reference: formLogin
e: C:\..\SecurityConfig.kt: (21, 13): Unresolved reference: httpBasic
build.gradle.kts:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "3.0.6"
id("io.spring.dependency-management") version "1.1.0"
kotlin("jvm") version "1.7.22"
kotlin("plugin.spring") version "1.7.22"
}
group = "com.example"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_17
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.jetbrains.kotlin:kotlin-reflect")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.springframework.security:spring-security-test")
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "17"
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
The link to the example project in the documentation doesn't point to a project where the Kotlin DSL is used. Instead the usual fluent-style API is used in this project.
Comment From: marcusdacoregio
Hi @helmbold, thanks for the report.
In order to use the Kotlin DSL you have to add import org.springframework.security.config.annotation.web.invoke to your class.
The IDE does not do a great job of figuring out that we want to use the Kotlin DSL.
I'll use this ticket to improve the documentation mentioning that the import should be added.