Add hasIpAddress to Kotlin DSL

Closes gh-10577
This commit is contained in:
brunodmartins
2023-11-13 18:36:53 -03:00
committed by Josh Cummings
parent ee14ba2da5
commit ea7c720ce7
3 changed files with 107 additions and 1 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,6 +26,7 @@ import org.springframework.security.config.annotation.web.configurers.AuthorizeH
import org.springframework.security.core.Authentication
import org.springframework.security.web.access.intercept.AuthorizationFilter
import org.springframework.security.web.access.intercept.RequestAuthorizationContext
import org.springframework.security.web.server.authorization.IpAddressAuthorizationManager
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher
import org.springframework.security.web.util.matcher.AnyRequestMatcher
import org.springframework.security.web.util.matcher.RequestMatcher
@@ -222,6 +223,13 @@ class AuthorizeHttpRequestsDsl : AbstractRequestMatcherDsl() {
return AuthorityAuthorizationManager.hasAnyRole(*roles)
}
/**
* Require a specific IP or range of IP addresses.
* @since 6.3
*/
fun hasIpAddress(ipAddress: String): AuthorizationManager<RequestAuthorizationContext> =
IpAddressAuthorizationManager.hasIpAddress(ipAddress)
/**
* Specify that URLs are allowed by anyone.
*/

View File

@@ -816,4 +816,41 @@ class AuthorizeHttpRequestsDslTests {
}
}
@Test
fun `request when ip address does not match then responds with forbidden`() {
this.spring.register(HasIpAddressConfig::class.java).autowire()
this.mockMvc.perform(get("/path")
.with { request ->
request.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error")
request.apply {
dispatcherType = DispatcherType.ERROR
}
})
.andExpect(status().isForbidden)
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
open class HasIpAddressConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
authorizeHttpRequests {
authorize(anyRequest, hasIpAddress("10.0.0.0/24"))
}
}
return http.build()
}
@RestController
internal class PathController {
@RequestMapping("/path")
fun path() {
}
}
}
}