【问题标题】:Recieving a object posted by HTTP.POST接收由 HTTP.POST 发布的对象
【发布时间】:2020-11-11 08:54:40
【问题描述】:

您好,我正在尝试为我的 spring 应用程序制作电子邮件确认 api 用户需要输入他/她的姓名、备注、公司/工作、电子邮件。后 收到这个对象我想发送一个确认链接到电子邮件。

这是 HTML 代码:

<form method="POST" th:object="${Signature}">
   <label>Name : </label>
   <input id="inputName" type="text" th:field="*{name}">
   <label>Note : </label>
   <input id="inputNote" type="text" th:field="*{note}">
   <br>
   <label>Company : </label>
   <input id="inputCompany" type="text" th:field="*{company}">
   <label>Contact Info : </label>
   <input id="inputContact" type="email" th:field="*{email}" placeholder="This info will not be shared">
   <button>Submit</button>
   <br>
</form>

这是控制器

@Controller
@RequestMapping("/")
public class RootController
{
   @GetMapping
   public String root(Model model)
   {
      model.addAttribute("Signature", new Signature());
      return "Public/Home";
   }
   
   @PostMapping
   public String signPosted(Signature s)
   {
      System.out.println("Post Received");
      
      return "redirect:/thanks";
   }
}

注意:即使应用程序在 root("/") 上,用户在发帖时也必须转到 /#contact

这是对象类

import lombok.Data;

import javax.validation.constraints.NotBlank;

@Data
public class Signature
{
   //@NotBlank(message="Name is required")
   private String name;
   
   private String note;
   
   //@NotBlank(message="Name is required")
   private String email;
   
   //@NotBlank(message="Name is required")
   private String company;
   
   public Signature(){}
   
   public Signature(String name,
                    String note,
                    String email,
                    String company)
   {
      this.name = name;
      this.note = note;
      this.email = email;
      this.company = company;
   }
}

当我点击提交按钮时,它会将您带到错误页面并且消息是

出现意外错误(type=Forbidden,status=403)。

我的安全配置是

http
    .authorizeRequests()
    .antMatchers("/admin/**")
    .authenticated()
    .antMatchers("/**")
    .permitAll()
    .anyRequest()
    .authenticated()
    .and()
    .httpBasic();

【问题讨论】:

    标签: spring spring-boot spring-security http-post thymeleaf


    【解决方案1】:

    这是因为您没有在 Spring Security 配置中禁用 CSRF 保护(为除 GET 之外的每个 HTTP 动词启用),同时您还没有在 HTML 表单中发送 CSRF 令牌。

    如果你想禁用 CSRF 保护,试试这个 Spring Security 配置:

    http
        .csrf().disable()
        .authorizeRequests()
        .antMatchers("/admin/**")
        .authenticated()
        .antMatchers("/**")
        .permitAll()
        .anyRequest()
        .authenticated()
        .and()
        .httpBasic();
    

    如果你想保持 CSRF 保护并在你的 HTML 表单中添加一个 CSRF 令牌,试试这个:

    <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
    

    【讨论】:

    • CSRF 是什么意思,为什么它有用?
    • 假设您登录了一个网站,黑客可以向您发送一个虚假 URL,如果您单击它,您将使用您的身份验证登录进行操作。 CSRF 防止此类网络浏览器的漏洞发生
    猜你喜欢
    • 1970-01-01
    • 2023-02-05
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 2018-04-21
    相关资源
    最近更新 更多