如何在4.3版本中实施CSRF?

时间:2017-04-24 05:42:40

标签: java spring jsp spring-mvc csrf

我是弹簧框架工作的新手。 java的。但我知道laravel框架&用laravel完成CSRF实施并且工作正常。

如何在4.3版本开始实施CSRF?

我参考了以下链接中的文档

https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html

这里我显示了我的示例代码

的web.xml

<web-app id = "WebApp_ID" version = "2.4"
   xmlns = "http://java.sun.com/xml/ns/j2ee" 
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://java.sun.com/xml/ns/j2ee 
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

   <display-name>Sample</display-name>

   <servlet>
      <servlet-name>dispatcher</servlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>

   <servlet-mapping>
      <servlet-name>dispatcher</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>
</web-app>

调度-servlet.xml中

<?xml version='1.0' encoding='UTF-8' ?>
<beans xmlns = "http://www.springframework.org/schema/beans"
    xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context = "http://www.springframework.org/schema/context"
    xmlns:mvc = "http://www.springframework.org/schema/mvc"
    xsi:schemaLocation = "http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <context:component-scan base-package = "com.controllers" />

    <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name = "prefix" value = "/WEB-INF/jsp/" />
        <property name = "suffix" value = ".jsp" />
    </bean>
    <mvc:annotation-driven/>
</beans>

PageController.java

    package com.controllers;

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.web.bind.annotation.ResponseBody;

@Controller
public class PageController
{
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String ShowIndexPage()
    {
        return "Login";
    }

    @RequestMapping(value = "/LoginAuth", method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String LoginAuth(HttpServletRequest HTTPRequest, HttpServletResponse HTTPResponse)
    {
        return "LoginAuth";
    }
}

WebSecurityConfig.java

package com.controllers;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
public class WebSecurityConfig extends
        WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf();
    }
}

我在Login.jsp文件标题中添加了CSRF令牌

    <!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Welcome to Spring Web MVC project</title>
        <meta name="_csrf" content="${_csrf.token}"/>
        <meta name="_csrf_header" content="${_csrf.headerName}"/>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    </head>
    <body>
        <div class="LoginPanel">
            <form role="form" action="LoginAuth">
                <input value="sample" type="text" name="Username" class="form-control" data-parsley-type="alphanum" placeholder="Username" required/>
                <button type="button" class="btn-block Signin btn btn-labeled1 btn-warning">
                    Sign in
                </button>
            </form>
        </div>
        <script>
        $(document).ready(function()
        {
            var Form = $(".LoginPanel").find("form");
            $(".LoginPanel").find("button.Signin").click(function(Event)
            {       
                Event.preventDefault();
                $.ajax(
                {
                    type: "POST",
                    url: "LoginAuth",
                    data: Form.serialize(),
                    beforeSend: function (xhr,settings)
                    {
                        var CSRFToken = $("meta[name='_csrf']").attr("content");console.log(CSRFToken);
                        var CSRFHeader = $("meta[name='_csrf_header']").attr("content");console.log(CSRFHeader);
                        xhr.setRequestHeader(CSRFHeader, CSRFToken);
                    },
                    success: function(ResponseData, textStatus, jqXHR)
                    {
                        console.log(ResponseData);alert("success");
                    },
                    error: function(jqXHR, textStatus, errorThrown)
                    {
                        console.log("Error");
                    }
                });
            });
        });
        </script>
    </body>
</html>

项目结构(在netbeans中)

enter image description here

项目建设&amp;运行没有错误 然后我从浏览器

查看页面源(login.jsp)代码
<meta name="_csrf" content=""/>
<meta name="_csrf_header" content=""/>

这些字段仍为空

1 个答案:

答案 0 :(得分:0)

检查csrf的spring安全配置,例如:

<http>
    <!-- ... -->
    <csrf token-repository-ref="tokenRepository"/>
</http>
<bean id="tokenRepository"
    class="org.springframework.security.web.csrf.CookieCsrfTokenRepository">
    <property name="sessionAttributeName" valud="_csrf"/>
    <property name="sessionAttributeName" valud="_csrf_header"/>
</bean>

此外,您还可以实现自定义CookieCsrfToekRepository。

simple spring-security.xml:

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <http auto-config="true">
        <intercept-url pattern="/admin**" access="ROLE_USER" />
        <form-login
            login-page="/login"
            default-target-url="/welcome"
            authentication-failure-url="/login?error"
            username-parameter="username"
            password-parameter="password" />
        <logout logout-success-url="/login?logout" />
        <!-- enable csrf protection -->
        <csrf token-repository-ref="tokenRepository"/>
    </http>

<bean id="tokenRepository"
    class="org.springframework.security.web.csrf.CookieCsrfTokenRepository">
    <property name="sessionAttributeName" valud="_csrf"/>
    <property name="sessionAttributeName" valud="_csrf_header"/>
</bean>

    <authentication-manager>
        <authentication-provider>
          <user-service>
            <user name="user" password="123456" authorities="ROLE_USER" />
          </user-service>
        </authentication-provider>
    </authentication-manager>

</beans:beans>