CSRF 全称是Cross-site request forgery,跨站请求伪造。
用户访问了带木马或类似脚本的网站页面后,如果电脑或手机的Web浏览器被控制,浏览器之前访问过的登录、注册、支付等网站接口就可能被非法利用。
CSRF Token 就是用来防止网站的接口被非法利用,token 是一个随机字符串,在浏览器的页面里保存为 hidden 或 cookies 值,服务端保存在 Session(或 Redis),token 有时效性,保存在 session 的,就是 session 的 timeout 值。
CSRF Token 原理,以登录页面为例,显示登录页面是一个 GET操作,点击 "登录"按钮后,就是提交一个 POST 操作。
在 GET 操作里一个随机 token1 隐藏在登录页面里 (服务器也保存着这个token2), POST 操作时要带上登录页面里隐藏的 token1,POST接口会检查 token1 是不是超时了,是不是和 token2相等,如果不满足条件,拒绝登录操作。
本文在 Springmvc+JSTL+JQuery基于拦截器的Login实例 的基础上,添加一个拦截器 CSRFInterceptor。
1. 开发环境
2. 在 IDEA上创建项目
3. 导入 spring-webmvc, servlet, jstl
4. 支持 SpringMVC
5. 支持静态资源 (html/js/css/images)
6. 添加 Login 拦截器
以上步骤 1 到 6,请参考 Springmvc+JSTL+JQuery基于拦截器的Login实例
7. 添加 CSRF 拦截器
1) 自定义2个注解 RefreshCSRFToken 和 VerifyCSRFToken
(1)添加 src/main/java/com/example/csrf/annotation/RefreshCSRFToken.java
package com.example.csrf.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ java.lang.annotation.ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface RefreshCSRFToken {
public abstract boolean refresh() default true;
}
(2) 添加 src/main/java/com/example/csrf/annotation/VerifyCSRFToken.java
package com.example.csrf.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ java.lang.annotation.ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface VerifyCSRFToken {
public abstract boolean verify() default true;
}
2) CSRF Token 操作类
添加 src/main/java/com/example/csrf/CSRFToken.java
package com.example.csrf;
import javax.servlet.http.HttpServletRequest;
import org.springframework.util.StringUtils;
public class CSRFToken {
private static String randomSource = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static int randomDefaultLen = 48;
private static int randomMinLen = 6;
private static String tokenTag = "springmvc_CSRFToken";
private static String tokenSessionTag = "springmvc_CSRFToken_session";
public static String getTokenTag() {
return tokenTag;
}
public static String getToken(HttpServletRequest request) {
String token = (String) request.getSession().getAttribute(tokenSessionTag );
if (StringUtils.isEmpty(token)) {
return "";
}
return token;
}
public static String generateToken(HttpServletRequest request) {
String token = (String) request.getSession().getAttribute(tokenSessionTag );;
if (StringUtils.isEmpty(token)) {
token = randomStr(randomDefaultLen);
request.getSession().setAttribute(tokenSessionTag , token);
}
return token;
}
public static boolean verifyToken(HttpServletRequest request) {
String token1 = request.getHeader(tokenTag);
if (StringUtils.isEmpty(token1)) {
token1 = request.getParameter(tokenTag);
}
String token2 = (String) request.getSession().getAttribute(tokenSessionTag );;
if (!StringUtils.isEmpty(token1) && token1.equals(token2)) {
return true;
}
return false;
}
public static void removeToken(HttpServletRequest request) {
request.getSession().removeAttribute(tokenSessionTag );
}
public static String randomStr(int len) {
if (len < randomMinLen)
len = randomMinLen;
String str = "";
for (int i=0; i<len; i++) {
int index = (int) (Math.random()*randomSource.length());
str += randomSource.substring(index, index+1);
}
return str;
}
}
*注 com/example/csrf 目录下的两个注解和一个操作类,是相对独立的功能,不依赖于 Springmvc。操作类 CSRFToken.java 里用到的 org.springframework.util.StringUtils 是可以去掉的,只需修改 CSRFToken.java:
if (StringUtils.isEmpty(x)) {
改成
if (x == null || x.isEmpty()) {
3) CSRF 拦截器类
添加 src/main/java/com/example/interceptor/CSRFInterceptor.java
package com.example.interceptor;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.example.csrf.CSRFToken;
import com.example.csrf.annotation.RefreshCSRFToken;
import com.example.csrf.annotation.VerifyCSRFToken;
public class CSRFInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// Verify token
Method method = ((HandlerMethod) handler).getMethod();
if (method.getAnnotation(VerifyCSRFToken.class) != null) {
if (!CSRFToken.verifyToken(request)) {
PrintWriter out = response.getWriter();
out.print("Error: invalid token or token expired");
response.flushBuffer();
return false;
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// Refresh token
if (modelAndView != null) {
Method method = ((HandlerMethod) handler).getMethod();
if (method.getAnnotation(RefreshCSRFToken.class) != null) {
String tokenTag = "<input type='hidden' name='" + CSRFToken.getTokenTag() + "' value='" + CSRFToken.generateToken(request) + "' />";
modelAndView.addObject(CSRFToken.getTokenTag(), tokenTag);
}
}
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception {
// TODO Auto-generated method stub
}
}
4) 把 CSRF 拦截器配置到 springmvc-beans.xml
修改 src/main/resources/springmvc-beans.xml
<beans ...>
...
<!-- Interceptors -->
<mvc:interceptors>
<!-- login -->
...
<!-- csrf -->
<mvc:interceptor>
<mvc:mapping path="/**" />
<mvc:exclude-mapping path="/static/**" />
<bean class="com.example.interceptor.CSRFInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
...
</beans>
5) 修改 Session timeout 时间,方便测试这里改成了1 分钟
修改 src/main/webapp/WEB-INF/web.xml
<web-app>
...
<!-- Session timeout, unit: minute -->
<session-config>
<session-timeout>1</session-timeout>
</session-config>
...
</web-app>
8. 视图和控制器
1) 添加 src/main/webapp/WEB-INF/jsp/home.jsp,该文件和 CSRF 不相关
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Home</title>
<script language="javascript" src="${pageContext.request.contextPath}/static/js/jquery-1.12.2.min.js"></script>
</head>
<body>
<h3>Home Page</h3>
<c:if test="${not empty sessionScope.logged_user}">
<p style="width: 100%; text-align: right;">Welcome ${sessionScope.logged_user}, <a href="${pageContext.request.contextPath}/logout">Logout</a></p>
</c:if>
<p> </p>
<c:if test="${not empty message}">
<p style="color: blue;">${message}</p>
</c:if>
<script type="text/javascript">
$(document).ready(function() {
console.log("Home Page");
});
</script>
</body>
</html>
2) 添加 src/main/webapp/WEB-INF/jsp/login.jsp,该文件和CSRF相关,注意黑体文字
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>
<script language="javascript" src="${pageContext.request.contextPath}/static/js/jquery-1.12.2.min.js"></script>
</head>
<body>
<h3>Login Page</h3>
<p> </p>
<c:if test="${not empty message}">
<p style="color: red;">${message}</p>
</c:if>
<form id="loginForm" method="post" action="${pageContext.request.contextPath}/login/post">
${springmvc_CSRFToken}
<p>Username: <input type="text" id="username" name="username" value="" /></p>
<p>Password: <input type="password" id="password" name="password" value="" /></p>
<p><input type="button" value="Login" onClick="javascript: login()" /></p>
</form>
<script type="text/javascript">
$(document).ready(function() {
console.log("Login Page");
});
function login() {
var username = $("#username").val();
if (username == '') {
alert("Please enter username");
$("#username").focus();
return;
}
var password = $("#password").val();
if (password == '') {
alert("Please enter password");
$("#password").focus();
return;
}
$("#loginForm").submit();
}
</script>
</body>
</html>
3) 添加 src/main/java/com/example/controller/IndexController.java,自定义CSRF注解就添加到该文件,注意黑体文字
package com.example.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
import com.example.csrf.annotation.RefreshCSRFToken;
import com.example.csrf.annotation.VerifyCSRFToken;
@Controller
@RequestMapping("/")
public class IndexController {
@RequestMapping(method = RequestMethod.GET)
public String home(ModelMap modelMap) {
modelMap.addAttribute("message", "Springmvc Login Demo");
return "home";
}
@RefreshCSRFToken
@RequestMapping(value="/login", method = RequestMethod.GET)
public String login() {
return "login";
}
@RefreshCSRFToken
@VerifyCSRFToken
@RequestMapping(value="/login/post", method = RequestMethod.POST)
public StringloginPost(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
String username = request.getParameter("username");
String password = request.getParameter("password");
if ("admin".equals(username) && "123456".equals(password)) {
session.setAttribute("logged_user", username);
//return "redirect:/"; // 拦截器无法监听到这种redirect, 使用下面的方式跳转
try {
response.sendRedirect("/");
} catch (IOException e) {
}
return null;
}
modelMap.addAttribute("message", "Invalid username or password");
return "login";
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(HttpServletRequest request) {
request.getSession().invalidate();
return "redirect:/login";
}
}
9. 运行
在IDEA里用 tomcat7-maven-plugin 运行 (参考IDEA创建Maven Webapp项) 。
访问 http://localhost:9090 会自动跳转到 http://localhost:9090/login
Username: admin
Password: 123456
可以在 login 页面上等待 > 1 分钟 (前面web.xml设置session timeout为一分钟),再点击 Login 按钮,测试 CSRF token 超时:
Error: invalid token or token expired
再访问 http://localhost:9090, 一分钟内输入用户名和密码,点击 Login