默认是开启了spring security 的CSRF功能,如果我们没有配置禁用,Spring Security CSRF 会针对 PATCH,POST,PUT 和 DELETE 方法进行防护。
对如下的请求是不防护的
spring security的CSRF功能_spring security
spring security的CSRF功能_spring security_02
可以看到,从request中获取token,所以我们在页面中进行传递,我们可以使用thymeleaf模板引擎

 <!--引入thymethef模板引擎-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

在登录页中增加隐藏域,携带_csrf进行提交

<!DOCTYPE html xmlns:th="http://www.thymeleaf.org/">
<html lang="en" >
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/test/login"method="post">
    <input type="hidden" th:if="${_csrf}!=null" th:value="${_csrf.token}" name="_csrf"/>
    用户名:<input type="text"name="username"/><br/>
    密码:<input type="password"name="password"/><br/>
    <input type="checkbox" name="remember-me"/>记住我
    <input type="submit"value="提交"/>
</form>
</body>
</html>

也可以如下 <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>

如果name不是remember-me,也可以进行设置,这个是上一讲的内容了
spring security的CSRF功能_spring security_03
我们如果没禁用csrf(默认开启),在表单上加上那段隐藏域代码就可以测试了。

注意点,如果开启了csrf功能,则登出功能需要使用表单post提交,而不能是之前的超链接。
spring security的CSRF功能_spring security_04