java如何避免csrf攻击 java csrf攻击

主机教程 建站分享 2年前 (2022-10-24) 193次浏览

文章摘要:java如何避免csrf攻击 java csrf攻击

在java中使用spring实现避免csrf攻击 通过将以下代码添加到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 {

}

}


声明:
若非注明,本站文章源于互联网收集整理和网友分享发布,如有侵权,请联系站长处理。
文章名称:java如何避免csrf攻击 java csrf攻击
文章链接:http://www.7966.org/post/15962.html
转载请注明出处

喜欢 (0)