Search code examples
springkotlinspring-securitykotlin-dsl

Match request method with Kotlin DSL for Spring Security


Spring Security provided Kotlin DSL for easier configuration. Here's an example from Spring Blog:

override fun configure(http: HttpSecurity?) {
    http {
        httpBasic {}
        authorizeRequests {
            authorize("/greetings/**", hasAuthority("ROLE_ADMIN"))
            authorize("/**", permitAll)
        }
    }
}

I want to allow only POST request to a particular path. In Java, you can do:

http
  .httpBasic().and()
  .authorizeRequests()
    .antMatchers(HttpMethod.POST, "/greetings").hasRole("ADMIN");

Any examples using Kotlin DSL?


Solution

  • Asked too early. Seems like I've found the solution after looking through source.

    Adding for future reference:

    override fun configure(http: HttpSecurity) {
        http {
            csrf { disable() }
            httpBasic {}
            authorizeRequests {
                authorize(AntPathRequestMatcher("/greetings", HttpMethod.POST.name),  hasRole("ADMIN"))
                authorize("/**", denyAll)
            }
        }
    }