java如何避免csrf攻击

1741
2021/1/13 9:32:43
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

java如何避免csrf攻击

在java中使用spring实现避免csrf攻击

通过将以下代码添加到Java项目中即可实现避免csrf攻击的功能。

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 {

}

}

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java怎么实现审核工作流功能