企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] # 1. 关闭CSRF保护演示 **1. 关闭CSRF保护** ```java @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { //关闭csrf http.csrf().disable(); } } ``` **2. controller层** ```java /** * post方式访问 */ @PostMapping("/v2/csrf/form") @ResponseBody public Account getAccount(Account account) { return account; } ``` **3. 表单以POST方式提交** ```html <form action="/v2/csrf/form" method="post"> id:<input type="text" name="id"/><br/> username:<input type="text" name="username"/><br/> password:<input type="text" name="password"/><br/> <input type="submit"/> </form> ``` **4. 结果** 可以正常提交。 <br/> # 2. 启用CSRF保护演示 **1. 启用CSRF保护** ```java @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { //不调用代码http.csrf().disable()就是开启csrf保护了 //http.csrf().disable(); } } ``` **2. controller层** ```java /** * post方式访问。 * Spring Security CSRF 只针对 PATCH,POST,PUT 和 DELETE 方法进行防护,GET方法不防护。 */ @PostMapping("/v2/csrf/form") @ResponseBody public Account getAccount(Account account) { return account; } ``` **3. 表单以POST方式提交** ```html <form action="/v2/csrf/form" method="post"> id:<input type="text" name="id"/><br/> username:<input type="text" name="username"/><br/> password:<input type="text" name="password"/><br/> <input type="submit"/> </form> ``` **4. 结果:表单不能提交,重定向到403页面** ``` Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Fri Jun 10 20:21:37 CST 2022 There was an unexpected error (type=Forbidden, status=403). Forbidden ``` **5. 在表单内添加csrf的隐藏域便可提交了** ```html <form action="/v2/csrf/form" method="post"> id:<input type="text" name="id"/><br/> username:<input type="text" name="username"/><br/> password:<input type="text" name="password"/><br/> <input type="hidden" th:if="${_csrf}!=null" th:value="${_csrf.token}" th:name="${_csrf.parameterName}"/> <input type="submit"/> </form> ``` <br/>