spring - spring boot项目提交注册表时报错403

标签 spring spring-boot thymeleaf

我在学习spring boot,写了一个注册表单,但是在idea中运行,提交表单的时候,浏览器出现了

There was an unexpected error (type=Forbidden, status=403). Forbidden



我在idea中使用spring initializr创建项目,选择web+jpa+h2+thymeleaf。
我定义了一个名为 Worker 的实体并在 ValidationMessages.properties 中设置了错误消息,这里是 Worker 实体
@Entity
public class Worker implements UserDetails {

    private static final long serialversionUID = 1L;

    @Id
    @NotNull
    @Size(min = 5, max = 16, message = "{username.size}")
    private String username;
    @NotNull
    @Size(min = 2, max = 30, message = "{firstName.size}")
    private String firstname;
    @NotNull
    @Size(min = 2, max = 30, message = "{lastName.size")
    private String lastname;
    @NotNull
    @Size(min = 5, max = 25,message = "{password.size}")
    private String password;
    @NotNull
    @Size(min = 2, max = 30, message = "{profession,size}")
    private String profession;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getProfession() {
        return profession;
    }

    public void setProfession(String profession) {
        this.profession = profession;
    }

    //UserDetails methods


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Arrays.asList(new SimpleGrantedAuthority("WORKER"));
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

和 WorkersRepository
public interface WorkersRepository extends JpaRepository<Worker, String> {
Worker findByUsername(String username);

}

我添加了 spring 安全性,并编写了配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private WorkersRepository workersRepository;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/submit").access("hasRole('WORKER')")
            .anyRequest().permitAll()
            .and()
            .formLogin()
            .loginPage("/login")
            .and()
            .logout()
            .logoutSuccessUrl("/")
            .and()
            .rememberMe()
            .tokenValiditySeconds(4838400)
            .key("workerKey");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws      Exception {
        auth.userDetailsService(new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String username) throws       UsernameNotFoundException {
                return workersRepository.findByUsername(username);
            }
        });
    }
}

如果注册输入出错, Controller 返回registerForm.html 要求用户重新正确输入。如果寄存器没有错误, Controller 重定向到“/”,一个简单的welcome.html。但是不管输入正确与否,我总是报错403。当我输入http://localhost:8080/时,我可以得到welcome.html,这是一个简单的页面,带有“欢迎!”字。我的 Controller 是
private WorkersRepository workersRepository;

@Autowired
public  WorkingHoursController(
        WorkersRepository workersRepository) {
    this.workersRepository = workersRepository;
}

@RequestMapping(method = RequestMethod.GET)
public String welcomePage() {
    return "welcome";
}

@RequestMapping(value = "/register", method = RequestMethod.GET)
public  String showRegistrationForm(Model model) {
    model.addAttribute(new Worker());
    return "registerForm";
}

@RequestMapping(value = "/register", method = RequestMethod.POST)
public String registrationProcessing(@Valid Worker worker, Errors errors, RedirectAttributes model) {
    if(errors.hasErrors()) {
        return "registerForm";
    }
    workersRepository.save(worker);
    model.addAttribute("username", worker.getUsername());
    model.addFlashAttribute("worker", worker);
    return "redirect:/";
}
...

我使用 thymeleaf 编写了 registerForm.html 并添加了错误验证。我的 registerForm.html 是
<form class="form-signin" method="post" th:object="${worker}">
<div class="errors" th:if="${#fields.hasErrors('*')}">
    <ul>
        <li th:each="err : ${#fields.errors('*')}"
            th:text="${err}">Input is in correct.</li>
    </ul>
</div>
<img class="mb-4" src="https://getbootstrap.com/assets/brand/bootstrap-solid.svg" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal">Please register</h1>

<!-- input username -->
<label for="inputUsername" th:class="${#fields.hasErrors('username')}? 'error'">Username</label>
<input type="text" id="inputUsername" th:field="*{username}" th:class="${#fields.hasErrors('username')}? 'error form-control':'form-control'" placeholder="Username">
...
<!-- input password -->
<label for="inputPassword" th:class="${#fields.hasErrors('password')}? 'error'">Password</label>
<input type="password" id="inputPassword" th:field="*{password}" th:class="${#fields.hasErrors('password')}? 'error form-control':'form-control'" placeholder="Password">
<div class="checkbox mb-3">
    <label>
        <input type="checkbox" id="remember-me" name="remember-me"> Remember me
    </label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Register</button>

在我在 thymeleaf 中添加验证并添加 spring 安全性之前,一切似乎都正常工作。

最佳答案

您没有在表单标签中放置任何操作。也许这就是你收到错误的原因。像这样把 Action 放在表单标签中

<form class="form-signin" action="#" th:action="@{/register}" method="post" th:object="${worker}">

关于spring - spring boot项目提交注册表时报错403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51021439/

相关文章:

java - 如何使用spring向不同的web服务发送并发请求

java - 如何在 Spring Boot 中使用 spring-security.xml 中的配置?

java - 从命令行注入(inject) map

spring-boot - img 未使用 Thymeleaf 和 Spring Boot 显示

java - 在 Spring 项目中实现 JSR-303 注释

java - 如何在我的项目中正确配置 Spring Security?

maven - Spring Boot Initializr : Maven project or Maven POM?

java - 如何在 Spring boot 中动态地向 JMSListener Annotation 添加不同的目的地?

thymeleaf - 如何使用 Thymeleaf 模板正确忽略/隐藏元素

spring-boot - 如何在 Spring Boot 下从 Thymeleaf 调用 @Service bean