Created
September 30, 2017 09:22
-
-
Save sbueringer/8261fda831332bcd379c65dfeda9f837 to your computer and use it in GitHub Desktop.
Kotlin magic for Spring Security Config
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// With a little bit of Kotlin magic | |
class WebSecurityConfig(val jwtValidator: JWTValidator) : WebSecurityConfigurerAdapter() { | |
override fun configure(http: HttpSecurity) = http { | |
matchRequests { !EndpointRequest.toAnyEndpoint() } | |
disable { csrf() } | |
disable { cors() } | |
authorizeRequests { | |
authenticate { anyRequest() } | |
} | |
addFilterBefore(JWTFilter(jwtValidator), UsernamePasswordAuthenticationFilter::class.java) | |
} | |
} | |
// Instead of | |
class WebSecurityConfig(val jwtValidator: JWTValidator) : WebSecurityConfigurerAdapter() { | |
override fun configure(http: HttpSecurity) { | |
http.requestMatcher(NegatedRequestMatcher(EndpointRequest.toAnyEndpoint())) | |
.csrf().disable() | |
.cors().disable() | |
.authorizeRequests().anyRequest().authenticated() | |
.and() | |
.addFilterBefore(JWTFilter(jwtValidator), UsernamePasswordAuthenticationFilter::class.java) | |
} | |
} | |
// Kotlin functions: | |
operator fun RequestMatcher.not() = NegatedRequestMatcher(this) | |
fun HttpSecurity.matchRequests(r: () -> RequestMatcher) = requestMatcher(r()) | |
fun <T : AbstractHttpConfigurer<T, B>, B : HttpSecurityBuilder<B>> disable(r: () -> AbstractHttpConfigurer<T, B>) = r().disable() | |
fun authenticate(r: () -> ExpressionUrlAuthorizationConfigurer<HttpSecurity>.AuthorizedUrl) = r().authenticated() | |
fun HttpSecurity.authorizeRequests(body: ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry.() -> Unit) = authorizeRequests().body() | |
operator fun HttpSecurity.invoke(body: HttpSecurity.() -> Unit) = body() | |
operator fun ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry.invoke(body: ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry.() -> Unit) = this.body() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment