Account registration creates a persistent application user from submitted identity and credential details. In a Spring application, Spring MVC presents and processes the form, while a repository saves the resulting User for later authentication. section 5.2.2
A typical registration flow connects these pieces:
- Expose GET /register to return the registration view. section 5.2.2
- Submit the form with POST /register; Spring MVC binds its fields to a RegistrationForm object. section 5.2.2
- Convert the form into a User, encoding the password through a PasswordEncoder before saving it with UserRepository. section 5.2.2
- Let a UserDetailsService retrieve users by username so Spring Security can authenticate more than one user. section 5.2.2
A registration form
A Thymeleaf view can collect username, password, password confirmation, full name, street, city, state, ZIP code, and phone number, then post the values to /register. section 5.2.2
Listing 5.5 A user registration controller
package tacos.security;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import tacos.data.UserRepository;
@Controller
@RequestMapping("/register")
public class RegistrationController {
private UserRepository userRepo;
private PasswordEncoder passwordEncoder;
public RegistrationController(
UserRepository userRepo, PasswordEncoder passwordEncoder) {
this.userRepo = userRepo;
this.passwordEncoder = passwordEncoder;
}
@GetMapping
public String registerForm() {
return "registration";
}
@PostMapping
public String processRegistration(RegistrationForm form) {
userRepo.save(form.toUser(passwordEncoder));
return "redirect:/login";
}
}
Inspect the controller structure that separates displaying the registration page from processing submitted form data. section 5.2.2
