Here I have the html code for a form. A form to create an event. It asks the user for a few information and after that he has to press the button create.
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head th:replace="fragments :: head"></head>
<body class="container">
<nav th:replace="fragments :: header"></nav>
<form method="post">
<div class="form-group">
<label>Name
<input th:field="${event.name}" class="form-control">
</label>
<p class="error" th:errors="${event.name}"></p>
</div>
<div class="form-group">
<label>Description
<input th:field="${event.eventDetails.description}" class="form-control">
</label>
<p class="error" th:errors="${event.eventDetails.description}"></p>
</div>
<div class="form-group">
<label>Contact Email
<input th:field="${event.eventDetails.contactEmail}" class="form-control">
</label>
<p class="error" th:errors="${event.eventDetails.contactEmail}"></p>
</div>
<div class="form-group">
<label>Category
<select th:field="${event.eventCategory}">
<option th:each="eventCategory : ${categories}"
th:value="${eventCategory.id}"
th:text="${eventCategory.name}"
></option>
</select>
<p class="error" th:errors="${event.eventCategory}"></p>
</label>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-success">
</div>
</form>
</body>
</html>
Here I have the java code for my form.
@GetMapping("create")
public String displayCreateEventForm(Model model){
model.addAttribute("title", "Create Event");
model.addAttribute(new Event());
model.addAttribute("categories", eventCategoryRepository.findAll());
return "events/create";
}
@PostMapping("create")
public String processCreateEventForm(@ModelAttribute @Valid Event newEvent, Errors errors, Model model){
if (errors.hasErrors()){
model.addAttribute("title", "Create Event");
return "events/create";
}
eventRepository.save(newEvent);
return "redirect:";
}
I don't know why after button is pressed it gives me an error like:
White label Error Page. This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Dec 29 00:24:57 EET 2020 There was an unexpected error (type=Forbidden, status=403). Forbidden.
The configuration class
package com.example.demo.config;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(
"/registration**",
"/js/**",
"/css/**",
"/img/**",
"/webjars/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login?logout")
.permitAll();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
auth.setUserDetailsService(userService);
auth.setPasswordEncoder(passwordEncoder());
return auth;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
}
As @dan1st mentioned it in the comment section, CSRF
is required in all form submission when using SpringSecurity (unless you disable it). To automatically add csrf token
in your form, a simple way is by using thymeleaf tags. As soon as thymeleaf detect its tags in a form, it will add csrf token in a hidden input when missing.
Here is an example
<form th:action="@{'your_post_path'}" method="POST" th:object="${yourModelAttributeEntity}">
...
</form>
You can add one of them or both
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.