如何更改测试的请求IP?

时间:2019-05-15 08:23:57

标签: java spring rest spring-boot kotlin

因此,作为this question的后续工作,我正在编写一些健全性测试,以验证Spring Boot的server.tomcat.remote-ip-header=X-Forwarded-For是否按预期工作...

@RestController
class RemoteAddressTesterController {
    @GetMapping("/remoteAddr")
    fun getRemoteAddress(request: HttpServletRequest):String = request.remoteAddr
}
@RunWith(SpringJUnit4ClassRunner::class)
@SpringBootTest(
    properties = ["server.tomcat.remote-ip-header=X-Forwarded-For"],
    webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
class RemoteAddressProviderIT{

    private val NON_LOCAL_IP_1 = "212.13.43.12"
    private val NON_LOCAL_IP_2 = "12.13.24.34"
    private val LOCAL_HOST = "127.0.0.1"

    @Inject
    lateinit var rest:TestRestTemplate

    private lateinit var headers:HttpHeaders

    @Before
    fun setup(){
        headers = HttpHeaders()
    }

有效:

    @Test
    fun withoutXFF_localhost() {
        val request = HttpEntity<Any>(headers)



        val remoteAddress = rest.exchange("/remoteAddr", HttpMethod.GET,request,String::class.java).body!!



        assertThat(remoteAddress).isEqualTo(LOCAL_HOST)
    }

这也可行:

    @Test
    fun XFF_clientWithProxy() {
        headers["X-Forwarded-For"] = "$NON_LOCAL_IP_2,$NON_LOCAL_IP_1"
        val request = HttpEntity<Any>(headers)



        val remoteAddress = rest.exchange("/remoteAddr", HttpMethod.GET,request,String::class.java).body!!



        assertThat(remoteAddress).isEqualTo(NON_LOCAL_IP_1)
    }

但是,这...

    @Test
    fun withoutXFF_remoteOrigin(){
        headers.origin = NON_LOCAL_IP_1
        headers.host = InetSocketAddress(NON_LOCAL_IP_1,8080)
        val request = HttpEntity<Any>(headers)



        val remoteAddress = rest.exchange("/remoteAddr", HttpMethod.GET,request,String::class.java).body!!



        assertThat(remoteAddress).isEqualTo(NON_LOCAL_IP_1)
    }

给我一​​个

org.junit.ComparisonFailure: 
Expected :"212.13.43.12"
Actual   :"127.0.0.1"

在这里,我的期望是IP是从IP标头获取的,而不是HTTP标头。我可以以某种方式更改该IP进行验证吗?

0 个答案:

没有答案