Freemarker中提交Spring Security表单CSRF保护问题

Freemarker中提交Spring Security表单CSRF保护问题

1. 问题描述

  • 这是一个普通的ftl文件提交表单
<form method="post" action="/login">
    <div><label> 用户名 : <input type="text" name="username"/> </label></div>
    <div><label> 密 码 : <input type="password" name="password"/> </label></div>
    <div><input type="submit" value="登录"/></div>
</form>
</body>
  • 如果以这种方式提交给后台Spring Security验证表单(其他设置处于默认情况),则会出现如下情况:Request method 'POST' not supported


2. 原因分析

主要是由于在Spring Security5中默认开启了CSRF保护,因此提交验证表单时,必须附带Token信息,同样你也可以在Spring Security的配置类中关闭保护(不推荐)

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
//关闭打开的csrf保护
    .csrf().disable();
}
}

3. 解决办法

在freemark的表单中,增加一行内容,如下:

<form method="post" action="/login">
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
    <div><label> 用户名 : <input type="text" name="username"/> </label></div>
    <div><label> 密 码 : <input type="password" name="password"/> </label></div>
    <div><input type="submit" value="登录"/></div>
</form>

4. 相关链接

猜你喜欢

转载自blog.csdn.net/u011857433/article/details/80311725
今日推荐