最近做接口開發(fā),需要跟第三方系統(tǒng)對接接口,基于第三方系統(tǒng)接口的保密性,需要將調(diào)用方的請求ip加入到他們的白名單中。由于我們公司平常使用的公網(wǎng)的ip是不固定的,每次都需要將代碼提交到固定的服務(wù)器上(服務(wù)器ip加入了第三方系統(tǒng)的白名單),頻繁的修改提交合并代碼和啟動服務(wù)器造成了額外的工作量,給接口聯(lián)調(diào)帶來了很大的阻礙。
正常的http請求
我們正常發(fā)起一個http的請求如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
import org.apache.http.httpentity; import org.apache.http.client.config.requestconfig; import org.apache.http.client.methods.closeablehttpresponse; import org.apache.http.client.methods.httppost; import org.apache.http.entity.stringentity; import org.apache.http.impl.client.closeablehttpclient; import org.apache.http.impl.client.httpclients; import org.apache.http.util.entityutils; public static string getpost4json(string url, string json) throws exception { closeablehttpclient httpclient = httpclients.createdefault(); httppost httppost = new httppost(url); /* 設(shè)置超時 */ requestconfig defaultrequestconfig = requestconfig.custom().setsockettimeout( 5000 ).setconnecttimeout( 5000 ).setconnectionrequesttimeout( 5000 ).build(); httppost.setconfig(defaultrequestconfig); httppost.addheader( "content-type" , "application/json;charset=utf-8" ); httppost.setentity( new stringentity(json, "utf-8" )); closeablehttpresponse response = null ; string result = null ; try { response = httpclient.execute(httppost); httpentity entity = response.getentity(); result = entityutils.tostring(entity, "utf-8" ); } catch (exception e) { throw e; } finally { if (response != null ) response.close(); httpclient.close(); } return result; } |
由于沒有加入白名單的原因,這樣的請求顯然無法調(diào)用到第三方的接口。這時候考慮能否將請求的ip改為白名單的一個ip,服務(wù)器在解析時拿到的不是正常的ip,這樣能否正常調(diào)用呢?
偽造http請求ip地址
我們知道正常的tcp/ip在通信過程中是無法改變源ip的,也就是說電腦獲取到的請求ip是不能改變的。但是可以通過偽造數(shù)據(jù)包的來源ip,即在http請求頭加一個x-forwarded-for的頭信息,這個頭信息配置的是ip地址,它代表客戶端,也就是http的請求端真實的ip。因此在上面代碼中加上如下代碼:
1
|
httppost.addheader( "x-forwarded-for" ,ip); |
服務(wù)端通過x-forwarded-for獲取請求ip,并且校驗ip安全性,代碼如下:
1
|
string ip = request.getheader( "x-forwarded-for" ); |
總結(jié)
通過請求頭追加x-forwarded-for頭信息可以偽造http請求ip地址。但是若服務(wù)器不直接信任并且不使用傳遞過來的 x-forward-for 值的時候偽造ip就不生效了。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://segmentfault.com/a/1190000016537618