Spring Boot After using Spring Security Solutions not POST to submit data

Project using a spring-boot + spring-security, with the thymeleaf page template.

The submission of this a very simple, but after clicking Submit error:

Suggested that the lack "_csrf" parameter or the 'X-CSRF-TOKEN' head.

[Reason]
using spring-security after attack enabled by default to prevent cross-domain functionality, any POST submit the form to the background must be tested with _csrf parameters, once came _csrf parameter is incorrect, the server will return 403 error;

Solution a: form a hidden field added in the form _csrf
<form Method = "POST" Action = "/ Login">
username: <INPUT type = "text" name = "the userName" />
<br />
password: <INPUT = type "password" name = "password" />
<br />
<- add a hidden field ->!
<INPUT type = "hidden" TH: name = "$ {_} csrf.parameterName" TH: value = " $ {_ csrf.token} "/>
<Button type =" Submit "> the Submit </ Button>
</ form>
the above code before the code corresponding to, add
<input type =" hidden "th : name =" $ {_ csrf. parameterName} "th: value =" $ {_ csrf.token} "/>
as posted back _csrf value;

Solution two (recommended) : Form form using th: form attributes, thymeleaf automatically generates _csrf hidden form fields in a form;
<form Method = "POST" TH: Action = "@ {/} Login">
username: <INPUT type = "text" name = "the userName" />
<br />
password: <INPUT type = "password" name = "password" />
<br />
<Button type = "Submit"> the Submit </ Button >
</ form>

解决方法三:关闭防跨域攻击功能,使用 http.csrf().disable():
package com.shawearn.blog.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
// 省略其他代码;
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// 代码省略...
}
}

 

excerpt

Guess you like

Origin www.cnblogs.com/lovechengyu/p/12195835.html