2022-01-26 Springmvc+JSTL+JQuery基于拦截器的CSRF Token实例

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>&nbsp;</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>&nbsp;</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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,470评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,393评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,577评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,176评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,189评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,155评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,041评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,903评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,319评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,539评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,703评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,417评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,013评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,664评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,818评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,711评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,601评论 2 353

推荐阅读更多精彩内容