銀行項目開發過程當中,基本都會採用 spring 框架,因此徹底能夠不用本身開發 filter 去攔截 csrf 攻擊的請求,而直接採用實現 spring 提供的 HandlerInterceptor 來實現。 從本質上來講,這也是一個 filter. 我這裏就直接實現它來 防止 csrf 攻擊.java
基本思路:
1. 用戶登陸以後,後臺程序生產一個 csrftoken 的 token ,放在 cookies 中,而且記錄在 session 中。
2. 當客戶端發出請求的訪問後臺程序的時候,通過本身實現的HandlerInterceptor 來攔截.
3. 攔截的基本方法是檢查請求的參數中是否有csrftoken ,並檢查這個值,是否合法有效(不爲空,而且獲得的參數等於cookies 中保存的值,並且還要等於session 中的值,那麼就是合法的)web
package com.yihaomen.intercepter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class CsrfIntercepter implements HandlerInterceptor {
public static final String CSRFNUMBER = "csrftoken";
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
String keyFromRequestParam = (String) request.getParameter(CSRFNUMBER);
String keyFromCookies="";
boolean result=false;
Cookie[] cookies = request.getCookies();
if(cookies!=null){
for (int i = 0; i < cookies.length; i++) {
String name = cookies[i].getName();
if(CSRFNUMBER.equals(name) ) {
keyFromCookies= cookies[i].getValue();
}
}
}
if((keyFromRequestParam!=null && keyFromRequestParam.length()>0 &&
keyFromRequestParam.equals(keyFromCookies) &&
keyFromRequestParam.equals((String)request.getSession().getAttribute(CSRFNUMBER)))) {
result=true;
}else{
request.getRequestDispatcher("/error/400").forward(request, response);
}
return result;
}
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, Exception arg3) throws Exception {
}
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
}
}
spring