詳解SpringBoot是如何保證接口安全的
為什么要保證接口安全
對于互聯(lián)網(wǎng)來說,只要你系統(tǒng)的接口會暴露在外網(wǎng),就避免不了接口安全問題。 如果你的接口在外網(wǎng)裸奔,只要讓黑客知道接口的地址和參數(shù)就可以調(diào)用,那簡直就是災(zāi)難。
舉個例子:你的網(wǎng)站用戶注冊的時候,需要填寫手機號,發(fā)送手機驗證碼,如果這個發(fā)送驗證碼的接口沒有經(jīng)過特殊安全處理,那這個短信接口早就被人盜刷不知道浪費多少錢了。
那如何保證接口安全呢?
一般來說,暴露在外網(wǎng)的api接口需要做到防篡改和防重放才能稱之為安全的接口。
防篡改
我們知道http 是一種無狀態(tài)的協(xié)議,服務(wù)端并不知道客戶端發(fā)送的請求是否合法,也并不知道請求中的參數(shù)是否正確。
舉個例子, 現(xiàn)在有個充值的接口,調(diào)用后可以給用戶增加對應(yīng)的余額。
http://localhost/api/user/recharge?user_id=1001&amount=10
如果非法用戶通過抓包獲取到接口參數(shù)后,修改user_id 或 amount的值就可以實現(xiàn)給任意賬戶添加余額的目的。
如何解決
采用https協(xié)議可以將傳輸?shù)拿魑倪M行加密,但是黑客仍然可以截獲傳輸?shù)臄?shù)據(jù)包,進一步偽造請求進行重放攻擊。如果黑客使用特殊手段讓請求方設(shè)備使用了偽造的證書進行通信,那么https加密的內(nèi)容也會被解密。
一般的做法有2種:
- 采用https方式把接口的數(shù)據(jù)進行加密傳輸,即便是被黑客破解,黑客也花費大量的時間和精力去破解。
- 接口后臺對接口的請求參數(shù)進行驗證,防止被黑客篡改;

- 步驟1:客戶端使用約定好的秘鑰對傳輸?shù)膮?shù)進行加密,得到簽名值sign1,并且將簽名值也放入請求的參數(shù)中,發(fā)送請求給服務(wù)端
- 步驟2:服務(wù)端接收到客戶端的請求,然后使用約定好的秘鑰對請求的參數(shù)再次進行簽名,得到簽名值sign2。
- 步驟3:服務(wù)端比對sign1和sign2的值,如果不一致,就認定為被篡改,非法請求。
防重放
防重放也叫防復(fù)用。簡單來說就是我獲取到這個請求的信息之后什么也不改,,直接拿著接口的參數(shù)去 重復(fù)請求這個充值的接口。此時我的請求是合法的, 因為所有參數(shù)都是跟合法請求一模一樣的。重放攻擊會造成兩種后果:
- 針對插入數(shù)據(jù)庫接口:重放攻擊,會出現(xiàn)大量重復(fù)數(shù)據(jù),甚至垃圾數(shù)據(jù)會把數(shù)據(jù)庫撐爆。
- 針對查詢的接口:黑客一般是重點攻擊慢查詢接口,例如一個慢查詢接口1s,只要黑客發(fā)起重放攻擊,就必然造成系統(tǒng)被拖垮,數(shù)據(jù)庫查詢被阻塞死。
對于重放攻擊一般有兩種做法:
基于timestamp的方案
每次HTTP請求,都需要加上timestamp參數(shù),然后把timestamp和其他參數(shù)一起進行數(shù)字簽名。因為一次正常的HTTP請求,從發(fā)出到達服務(wù)器一般都不會超過60s,所以服務(wù)器收到HTTP請求之后,首先判斷時間戳參數(shù)與當前時間比較,是否超過了60s,如果超過了則認為是非法請求。
一般情況下,黑客從抓包重放請求耗時遠遠超過了60s,所以此時請求中的timestamp參數(shù)已經(jīng)失效了。 如果黑客修改timestamp參數(shù)為當前的時間戳,則sign1參數(shù)對應(yīng)的數(shù)字簽名就會失效,因為黑客不知道簽名秘鑰,沒有辦法生成新的數(shù)字簽名。

但是這種方式的漏洞也是顯而易見,如果在60s之內(nèi)進行重放攻擊,那就沒辦法了,所以這種方式不能保證請求僅一次有效。
老鳥們一般會采取下面這種方案,既可以解決接口重放問題,又可以解決一次請求有效的問題。
基于nonce + timestamp 的方案
nonce的意思是僅一次有效的隨機字符串,要求每次請求時該參數(shù)要保證不同。實際使用用戶信息+時間戳+隨機數(shù)等信息做個哈希之后,作為nonce參數(shù)。
此時服務(wù)端的處理流程如下:
- 去 redis 中查找是否有 key 為
nonce:{nonce}的 string - 如果沒有,則創(chuàng)建這個 key,把這個 key 失效的時間和驗證 timestamp 失效的時間一致,比如是 60s。
- 如果有,說明這個 key 在 60s 內(nèi)已經(jīng)被使用了,那么這個請求就可以判斷為重放請求。

這種方案nonce和timestamp參數(shù)都作為簽名的一部分傳到后端,基于timestamp方案可以讓黑客只能在60s內(nèi)進行重放攻擊,加上nonce隨機數(shù)以后可以保證接口只能被調(diào)用一次,可以很好的解決重放攻擊問題。
代碼實現(xiàn)
接下來以SpringBoot項目為例看看如何實現(xiàn)接口的防篡改和防重放功能。
1、構(gòu)建請求頭對象
@Data
@Builder
public class RequestHeader {
private String sign ;
private Long timestamp ;
private String nonce;
}2、工具類從HttpServletRequest獲取請求參數(shù)
@Slf4j
@UtilityClass
public class HttpDataUtil {
/**
* post請求處理:獲取 Body 參數(shù),轉(zhuǎn)換為SortedMap
*
* @param request
*/
public SortedMap<String, String> getBodyParams(final HttpServletRequest request) throws IOException {
byte[] requestBody = StreamUtils.copyToByteArray(request.getInputStream());
String body = new String(requestBody);
return JsonUtil.json2Object(body, SortedMap.class);
}
?
?
/**
* get請求處理:將URL請求參數(shù)轉(zhuǎn)換成SortedMap
*/
public static SortedMap<String, String> getUrlParams(HttpServletRequest request) {
String param = "";
SortedMap<String, String> result = new TreeMap<>();
?
if (StringUtils.isEmpty(request.getQueryString())) {
return result;
}
?
try {
param = URLDecoder.decode(request.getQueryString(), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
?
String[] params = param.split("&");
for (String s : params) {
String[] array=s.split("=");
result.put(array[0], array[1]);
}
return result;
}
}這里的參數(shù)放入SortedMap中對其進行字典排序,前端構(gòu)建簽名時同樣需要對參數(shù)進行字典排序。
3、簽名驗證工具類
@Slf4j
@UtilityClass
public class SignUtil {
/**
* 驗證簽名
* 驗證算法:把timestamp + JsonUtil.object2Json(SortedMap)合成字符串,然后MD5
*/
@SneakyThrows
public boolean verifySign(SortedMap<String, String> map, RequestHeader requestHeader) {
String params = requestHeader.getNonce() + requestHeader.getTimestamp() + JsonUtil.object2Json(map);
return verifySign(params, requestHeader);
}
?
/**
* 驗證簽名
*/
public boolean verifySign(String params, RequestHeader requestHeader) {
log.debug("客戶端簽名: {}", requestHeader.getSign());
if (StringUtils.isEmpty(params)) {
return false;
}
log.info("客戶端上傳內(nèi)容: {}", params);
String paramsSign = DigestUtils.md5DigestAsHex(params.getBytes()).toUpperCase();
log.info("客戶端上傳內(nèi)容加密后的簽名結(jié)果: {}", paramsSign);
return requestHeader.getSign().equals(paramsSign);
}
}4、HttpServletRequest包裝類
public class SignRequestWrapper extends HttpServletRequestWrapper {
//用于將流保存下來
private byte[] requestBody = null;
?
public SignRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
requestBody = StreamUtils.copyToByteArray(request.getInputStream());
}
?
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody);
?
return new ServletInputStream() {
@Override
public boolean isFinished() {
return false;
}
?
@Override
public boolean isReady() {
return false;
}
?
@Override
public void setReadListener(ReadListener readListener) {
?
}
?
@Override
public int read() throws IOException {
return bais.read();
}
};
?
}
?
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
}防篡改和防重放我們會通過SpringBoot Filter來實現(xiàn),而編寫的filter過濾器需要讀取request數(shù)據(jù)流,但是request數(shù)據(jù)流只能讀取一次,需要自己實現(xiàn)HttpServletRequestWrapper對數(shù)據(jù)流包裝,目的是將request流保存下來。
5、創(chuàng)建過濾器實現(xiàn)安全校驗
@Configuration
public class SignFilterConfiguration {
@Value("${sign.maxTime}")
private String signMaxTime;
?
//filter中的初始化參數(shù)
private Map<String, String> initParametersMap = new HashMap<>();
?
@Bean
public FilterRegistrationBean contextFilterRegistrationBean() {
initParametersMap.put("signMaxTime",signMaxTime);
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(signFilter());
registration.setInitParameters(initParametersMap);
registration.addUrlPatterns("/sign/*");
registration.setName("SignFilter");
// 設(shè)置過濾器被調(diào)用的順序
registration.setOrder(1);
return registration;
}
?
@Bean
public Filter signFilter() {
return new SignFilter();
}
}@Slf4j
public class SignFilter implements Filter {
@Resource
private RedisUtil redisUtil;
?
//從fitler配置中獲取sign過期時間
private Long signMaxTime;
?
private static final String NONCE_KEY = "x-nonce-";
?
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
?
log.info("過濾URL:{}", httpRequest.getRequestURI());
?
HttpServletRequestWrapper requestWrapper = new SignRequestWrapper(httpRequest);
//構(gòu)建請求頭
RequestHeader requestHeader = RequestHeader.builder()
.nonce(httpRequest.getHeader("x-Nonce"))
.timestamp(Long.parseLong(httpRequest.getHeader("X-Time")))
.sign(httpRequest.getHeader("X-Sign"))
.build();
?
//驗證請求頭是否存在
if(StringUtils.isEmpty(requestHeader.getSign()) || ObjectUtils.isEmpty(requestHeader.getTimestamp()) || StringUtils.isEmpty(requestHeader.getNonce())){
responseFail(httpResponse, ReturnCode.ILLEGAL_HEADER);
return;
}
?
/*
* 1.重放驗證
* 判斷timestamp時間戳與當前時間是否操過60s(過期時間根據(jù)業(yè)務(wù)情況設(shè)置),如果超過了就提示簽名過期。
*/
long now = System.currentTimeMillis() / 1000;
?
if (now - requestHeader.getTimestamp() > signMaxTime) {
responseFail(httpResponse,ReturnCode.REPLAY_ERROR);
return;
}
?
//2. 判斷nonce
boolean nonceExists = redisUtil.hasKey(NONCE_KEY + requestHeader.getNonce());
if(nonceExists){
//請求重復(fù)
responseFail(httpResponse,ReturnCode.REPLAY_ERROR);
return;
}else {
redisUtil.set(NONCE_KEY+requestHeader.getNonce(), requestHeader.getNonce(), signMaxTime);
}
?
?
boolean accept;
SortedMap<String, String> paramMap;
switch (httpRequest.getMethod()){
case "GET":
paramMap = HttpDataUtil.getUrlParams(requestWrapper);
accept = SignUtil.verifySign(paramMap, requestHeader);
break;
case "POST":
paramMap = HttpDataUtil.getBodyParams(requestWrapper);
accept = SignUtil.verifySign(paramMap, requestHeader);
break;
default:
accept = true;
break;
}
if (accept) {
filterChain.doFilter(requestWrapper, servletResponse);
} else {
responseFail(httpResponse,ReturnCode.ARGUMENT_ERROR);
return;
}
?
}
?
private void responseFail(HttpServletResponse httpResponse, ReturnCode returnCode) {
ResultData<Object> resultData = ResultData.fail(returnCode.getCode(), returnCode.getMessage());
WebUtils.writeJson(httpResponse,resultData);
}
?
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String signTime = filterConfig.getInitParameter("signMaxTime");
signMaxTime = Long.parseLong(signTime);
}
}6、Redis工具類
@Component
public class RedisUtil {
@Resource
private RedisTemplate<String, Object> redisTemplate;
?
/**
* 判斷key是否存在
* @param key 鍵
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return Boolean.TRUE.equals(redisTemplate.hasKey(key));
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
?
?
/**
* 普通緩存放入并設(shè)置時間
* @param key 鍵
* @param value 值
* @param time 時間(秒) time要大于0 如果time小于等于0 將設(shè)置無限期
* @return true成功 false 失敗
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
?
/**
* 普通緩存放入
* @param key 鍵
* @param value 值
* @return true成功 false失敗
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
?
}以上就是詳解SpringBoot是如何保證接口安全的的詳細內(nèi)容,更多關(guān)于SpringBoot保證接口安全的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
聊聊BeanUtils.copyProperties和clone()方法的區(qū)別
這篇文章主要介紹了聊聊BeanUtils.copyProperties和clone()方法的區(qū)別,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09
mybatis mapper.xml獲取insert后的自增ID問題
這篇文章主要介紹了mybatis mapper.xml獲取insert后的自增ID問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05
如何在mybatis中向BLOB字段批量插入數(shù)據(jù)
這篇文章主要介紹了如何在mybatis中向BLOB字段批量插入數(shù)據(jù)的相關(guān)知識,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2020-10-10
Spring Boot項目添加外部Jar包以及配置多數(shù)據(jù)源的完整步驟
這篇文章主要給大家介紹了關(guān)于Spring Boot項目添加外部Jar包以及配置多數(shù)據(jù)源的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2020-06-06

