在java中使用spring实现避免csrf攻击通过将以下代码添加到Java项目中即可实现避免csrf攻击的功能。package com.yihaomen.intercepter;import javax.servlet.Http.Cook
在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 {
}
}
--结束END--
本文标题: java如何避免csrf攻击
本文链接: https://lsjlt.com/news/115332.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0