Java 如何在Spring4.3中实现CSRF?

Java 如何在Spring4.3中实现CSRF?,java,spring,jsp,spring-mvc,csrf,Java,Spring,Jsp,Spring Mvc,Csrf,我是spring框架和java的新手。但是我知道laravel框架&使用laravel实现CSRF,并且工作正常 如何在Spring4.3中实现CSRF 我参考了下面链接中的文档 这里我展示了我的示例代码 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/XMLSchem

我是spring框架和java的新手。但是我知道laravel框架&使用laravel实现CSRF,并且工作正常

如何在Spring4.3中实现CSRF

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

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

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>
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>

欢迎来到SpringWebMVC项目
登录
$(文档).ready(函数()
{
var Form=$(“.LoginPanel”).find(“Form”);
$(.LoginPanel”).find(“button.sign”).click(函数(事件)
{       
Event.preventDefault();
$.ajax(
{
类型:“POST”,
网址:“登录号”,
数据:Form.serialize(),
发送前:功能(xhr、设置)
{
var CSRFToken=$(“meta[name=''u csrf']”)attr(“content”);console.log(CSRFToken);
var CSRFHeader=$(“meta[name=''u csrf_header']”)attr(“content”);console.log(CSRFHeader);
setRequestHeader(CSRFHeader,CSRFToken);
},
成功:函数(ResponseData、textStatus、jqXHR)
{
console.log(ResponseData);警报(“成功”);
},
错误:函数(jqXHR、textStatus、errorshown)
{
控制台日志(“错误”);
}
});
});
});
项目结构(在netbeans中)

项目生成并运行,无错误 然后我从浏览器中查看页面源代码(login.jsp)

<meta name="_csrf" content=""/>
<meta name="_csrf_header" content=""/>


这些字段仍然为空

请检查您的spring security配置中的csrf,如下所示:

<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>

检查您的spring security配置是否有csrf,如下所示:

<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>


没有安全筛选器,因此不会应用安全性。没有安全筛选器,因此不会应用安全性。在哪里添加这些配置?“dispatcher servlet.xml”在spring security xml文件中吗?该文件的名称通常为spring-security.xml,在何处添加这些配置?是“dispatcher servlet.xml”吗?在spring安全xml文件中,该文件的名称通常为spring-security.xml