I am relatively new to Srping Security Framework. During my learning period I have tried to implement a basic authentication security feature for a private api endpoint /private/**
. The application also contains a public api /public/**
where not filters are applied and is accessible for everyone.
My code is presented below:
Employee.kt
data class Employee(val name: String, val age: Int)
SpringConfig.kt
@Configuration
@EnableWebSecurity
class SecurityConfig {
@Bean
fun securityFilterChain(http: HttpSecurity) : SecurityFilterChain? {
http
.authorizeHttpRequests { authz ->
authz
.antMatchers("/private/**").authenticated()
}
.formLogin(withDefaults())
return http.build()
}
@Bean
fun users(): InMemoryUserDetailsManager {
return InMemoryUserDetailsManager(
User.withUsername("john")
.password("{noop}password")
.authorities("read")
.build()
)
}
}
End points: PublicEmployee.kt
@RestController
@RequestMapping("/public")
class PublicEmployeeResource {
@GetMapping("/employee")
fun getEmployee(): ResponseEntity<Employee> {
val employee = Employee(name="John", age=42)
return ResponseEntity.ok(employee)
}
}
PrivateEmployee.kt
@RestController
@RequestMapping("/private")
class PrivateEmployeeResource {
@GetMapping("/employee")
fun getEmployee(principal: Principal): ResponseEntity<Employee> {
val employee = Employee(name="John", age=42)
println("Principal is ${principal}")
return ResponseEntity.ok(employee)
}
}
When I am using .formLogin(withDefaults())
for authentication, I get the below picture and I can pass the user and password as stated InMemoryUserDetailsManager
.
However if I change the autnetication to httpBasic()
I do get the response from Employee object without any authentication.
Not sure what I am doing wrong.
Also I have read that WebConfigurerAdapter() is going to be deprectated. How I could setup multiple filters for specific url patterns in then ?