(There are two code blocks below. The only difference between them are marked with comments.)
I have successfully configured spring security without understanding much as below:
@EnableWebSecurity
@Configuration
class SecurityConfig {
@Bean
fun publicEndpointSecurityFilterChain(http: HttpSecurity): SecurityFilterChain = http
// only this part is different! (from)
.securityMatchers{
it.requestMatchers(*permittedUrls)
}
// only this part is different! (to)
.csrf().disable()
.headers {
it.frameOptions().sameOrigin()
it.contentSecurityPolicy("frame-ancestors 'self'")
}
.build()
@Bean
fun securityFilterChain(http: HttpSecurity): SecurityFilterChain = http
.authorizeHttpRequests {
it.anyRequest()
.authenticated()
}
.oauth2ResourceServer { oauth2 ->
oauth2.jwt()
}
.csrf().disable()
.headers {
it.frameOptions().sameOrigin()
it.contentSecurityPolicy("frame-ancestors 'self'")
}
.build()
}
With this configuration, the server gives 401 http status code for all endpoints except permittedUrls
when the request headers are with invalid jwt or without token at all.
Now please check a configuration below I have tried before my lucky success:
@EnableWebSecurity
@Configuration
class SecurityConfig {
@Bean
// @Order(0) does not make a difference here.
fun publicEndpointSecurityFilterChain(http: HttpSecurity): SecurityFilterChain = http
// only this part is different! (from)
.authorizeHttpRequests{
it.requestMatchers(*permittedUrls)
.permitAll()
}
// only this part is different! (to)
.csrf().disable()
.headers {
it.frameOptions().sameOrigin()
it.contentSecurityPolicy("frame-ancestors 'self'")
}
.build()
@Bean
fun securityFilterChain(http: HttpSecurity): SecurityFilterChain = http
.authorizeHttpRequests {
it.anyRequest()
.authenticated()
}
.oauth2ResourceServer { oauth2 ->
oauth2.jwt()
}
.csrf().disable()
.headers {
it.frameOptions().sameOrigin()
it.contentSecurityPolicy("frame-ancestors 'self'")
}
.build()
}
This configuration gives 403 http status code instead of 401. I don’t understand why. It has nothing to do with @Order since even with @Order(0)
on the first method, the client still receives 403 status code.
Could you please tell me what makes a difference?
ps. If you are super kind please explain when to use securityMatchers
. I have read Spring Security: securityMatcher vs requestMatcher and want to make sure this comment is right.
9