SpringSecurity的如何拦截提交POST请求

从Spring Security3.2开始,默认就会启用CSRF攻击。 
  Spring Security通过一个同步token的方式来实现CSRF防护。它会拦截状态变化的请求并检查CSRF token。如果请求不包含CSRF token,或token不能与服务器端的token相匹配,请求将会失败,并抛出CsrfException。 

Spring Security已经简化了将token放到请求的属性中这一任务:

  • 使用JSP作为页面模板的话,要做的事非常类似:
<input type="hidden" name="${_csrf.parameterName}"  value="${_csrf.token}" />

       如果使用Spring表单绑定标签的话,标签会自动为我们添加隐藏的CSRF token标签。

例如一个用from表单提交一个post的请求,想要通过验证必须添加上:

<input type="hidden" name="${_csrf.parameterName}"  value="${_csrf.token}" />

下面给一个例子:

           <form class="form-new-pwd-wrapper"  action="${pageContext.request.contextPath }/resetNew" method="POST">
                        <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
                        <div class="pwd-input-container-wrapper">
                            <span class="pwd-title-wrapper">新密码&nbsp;:</span>&nbsp;&nbsp;<input id="pwd"
                                class="password-input-wrapper" type="password" name="password"  placeholder="&nbsp;请输入新的密码">
                        </div>

                        <div class="pwd-input-container-wrapper">
                            <span class="pwd-title-wrapper">再次输入:</span> <input id="confirm-pwd"
                                class="password-input-wrapper" type="password" placeholder="&nbsp;请再次输入新的密码">
                        </div>

                        <input class="submit-request-wrapper" type="submit" value="确认修改密码" onclick="return check();">
              </form>

 如果上属例子中没有添加上第二行的代码,

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />

则默认会被系统拦截,进入到预先设置的登录界面。

 
原文地址:https://www.cnblogs.com/wyf-love-dch/p/7216155.html