Proses Pendaftaran Dengan Keamanan Musim Semi

Artikel ini adalah bagian dari serial: • Tutorial Pendaftaran Keamanan Musim Semi

• Proses Pendaftaran Dengan Keamanan Musim Semi (artikel saat ini) • Pendaftaran - Aktifkan Akun Baru melalui Email

• Pendaftaran Keamanan Musim Semi - Kirim Ulang Email Verifikasi

• Pendaftaran dengan Spring Security - Encoding Sandi

• API Pendaftaran menjadi RESTful

• Keamanan Musim Semi - Atur Ulang Kata Sandi Anda

• Pendaftaran - Kekuatan dan Aturan Kata Sandi

• Memperbarui Kata Sandi Anda

1. Ikhtisar

Di artikel ini, kami akan menerapkan proses pendaftaran dasar dengan Keamanan Musim Semi. Ini membangun di atas konsep yang dieksplorasi di artikel sebelumnya, di mana kita melihat login.

Tujuannya di sini adalah untuk menambahkan proses pendaftaran lengkap yang memungkinkan pengguna untuk mendaftar, memvalidasi, dan menyimpan data pengguna.

2. Halaman Pendaftaran

Pertama - mari terapkan halaman registrasi sederhana yang menampilkan bidang-bidang berikut :

  • nama ( nama depan dan belakang)
  • surel
  • kata sandi (dan bidang konfirmasi kata sandi)

Contoh berikut menunjukkan halaman registrasi.html sederhana :

Contoh 2.1.

form

first

Validation error

last

Validation error

email

Validation error

password

Validation error

confirm submit login

3. Objek DTO Pengguna

Kami membutuhkan Objek Transfer Data untuk mengirim semua informasi pendaftaran ke backend Spring kami. The DTO objek harus memiliki semua informasi yang kami akan butuhkan nanti pada saat kita membuat dan mengisi kami Pengguna objek:

public class UserDto { @NotNull @NotEmpty private String firstName; @NotNull @NotEmpty private String lastName; @NotNull @NotEmpty private String password; private String matchingPassword; @NotNull @NotEmpty private String email; // standard getters and setters }

Perhatikan kami menggunakan anotasi javax.validation standar pada bidang objek DTO. Nanti, kami juga akan menerapkan anotasi validasi kustom kami sendiri untuk memvalidasi format alamat email serta untuk konfirmasi kata sandi. (lihat Bagian 5)

4. Pengontrol Pendaftaran

Sebuah Sign-Up link di masuk halaman akan membawa pengguna ke pendaftaran halaman. Bagian belakang untuk halaman tersebut berada di pengontrol pendaftaran dan dipetakan ke "/ pengguna / pendaftaran" :

Contoh 4.1. - Metode showRegistration

@GetMapping("/user/registration") public String showRegistrationForm(WebRequest request, Model model) { UserDto userDto = new UserDto(); model.addAttribute("user", userDto); return "registration"; }

Ketika controller menerima permintaan "/ user / Registration" , ia membuat objek UserDto baru yang akan mendukung formulir pendaftaran , mengikatnya dan mengembalikannya - cukup mudah.

5. Memvalidasi Data Pendaftaran

Selanjutnya - mari kita lihat validasi yang akan dilakukan pengontrol saat mendaftarkan akun baru:

  1. Semua bidang wajib diisi (Tidak ada bidang kosong atau nol)
  2. Alamat email valid (dalam format yang baik)
  3. Bidang konfirmasi kata sandi cocok dengan bidang kata sandi
  4. Akun tersebut belum ada

5.1. Validasi Built-In

Untuk pemeriksaan sederhana, kita akan menggunakan anotasi validasi out of the box bean pada objek DTO - anotasi seperti @NotNull , @NotEmpty , dll.

Untuk memicu proses validasi, kami hanya akan membuat anotasi objek di lapisan pengontrol dengan anotasi @Valid :

public ModelAndView registerUserAccount( @ModelAttribute("user") @Valid UserDto userDto, HttpServletRequest request, Errors errors) { ... }

5.2. Validasi Kustom untuk Memeriksa Validitas Email

Selanjutnya - mari validasi alamat email dan pastikan format yang benar. Kita akan membuat validator khusus untuk itu, serta anotasi validasi khusus - sebut saja @ValidEmail .

Sidenote singkat di sini - kami memutar anotasi kustom kami sendiri daripada @Email Hibernate karena Hibernate menganggap format alamat intranet lama: [email dilindungi] sebagai valid (lihat artikel Stackoverflow), yang tidak baik.

Berikut penjelasan validasi email dan validator kustomnya:

Contoh 5.2.1. - Anotasi Kustom untuk Validasi Email

@Target({TYPE, FIELD, ANNOTATION_TYPE}) @Retention(RUNTIME) @Constraint(validatedBy = EmailValidator.class) @Documented public @interface ValidEmail { String message() default "Invalid email"; Class[] groups() default {}; Class[] payload() default {}; }

Perhatikan bahwa kami telah mendefinisikan anotasi di tingkat FIELD - karena di situlah penerapannya secara konseptual.

Contoh 5.2.2. - The Custom EmailValidato r:

public class EmailValidator implements ConstraintValidator { private Pattern pattern; private Matcher matcher; private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-+]+ (.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(.[A-Za-z0-9]+)* (.[A-Za-z]{2,})$"; @Override public void initialize(ValidEmail constraintAnnotation) { } @Override public boolean isValid(String email, ConstraintValidatorContext context){ return (validateEmail(email)); } private boolean validateEmail(String email) { pattern = Pattern.compile(EMAIL_PATTERN); matcher = pattern.matcher(email); return matcher.matches(); } }

Sekarang mari gunakan anotasi baru pada implementasi UserDto kita :

@ValidEmail @NotNull @NotEmpty private String email;

5.3. Menggunakan Validasi Kustom untuk Konfirmasi Kata Sandi

Kami juga memerlukan anotasi dan validator khusus untuk memastikan bahwa bidang kata sandi dan kata sandi cocok :

Contoh 5.3.1. - Anotasi Kustom untuk Memvalidasi Konfirmasi Kata Sandi

@Target({TYPE,ANNOTATION_TYPE}) @Retention(RUNTIME) @Constraint(validatedBy = PasswordMatchesValidator.class) @Documented public @interface PasswordMatches { String message() default "Passwords don't match"; Class[] groups() default {}; Class[] payload() default {}; }

Notice that the @Target annotation indicates that this is a TYPE level annotation. This is because we need the entire UserDto object to perform the validation.

The custom validator that will be called by this annotation is shown below:

Example 5.3.2. The PasswordMatchesValidator Custom Validator

public class PasswordMatchesValidator implements ConstraintValidator { @Override public void initialize(PasswordMatches constraintAnnotation) { } @Override public boolean isValid(Object obj, ConstraintValidatorContext context){ UserDto user = (UserDto) obj; return user.getPassword().equals(user.getMatchingPassword()); } }

Now, the @PasswordMatches annotation should be applied to our UserDto object:

@PasswordMatches public class UserDto { ... }

All custom validations are of course evaluated along with all standard annotations when the entire validation process runs.

5.4. Check That the Account Doesn't Already Exist

The fourth check we'll implement is verifying that the email account doesn't already exist in the database.

This is performed after the form has been validated and it's done with the help of the UserService implementation.

Example 5.4.1. – The Controller's createUserAccount Method Calls the UserService Object

@PostMapping("/user/registration") public ModelAndView registerUserAccount (@ModelAttribute("user") @Valid UserDto userDto, HttpServletRequest request, Errors errors) { try { User registered = userService.registerNewUserAccount(userDto); } catch (UserAlreadyExistException uaeEx) { mav.addObject("message", "An account for that username/email already exists."); return mav; } // rest of the implementation } 

Example 5.4.2. – UserService Checks for Duplicate Emails

@Service public class UserService implements IUserService { @Autowired private UserRepository repository; @Transactional @Override public User registerNewUserAccount(UserDto userDto) throws UserAlreadyExistException { if (emailExist(userDto.getEmail())) { throw new UserAlreadyExistException( "There is an account with that email address: " + userDto.getEmail()); } ... // the rest of the registration operation } private boolean emailExist(String email) { return userRepository.findByEmail(email) != null; } }

The UserService relies on the UserRepository class to check if a user with a given email address already exists in the database.

Now – the actual implementation of the UserRepository in the persistence layer isn't relevant for the current article. One quick way is, of course, to use Spring Data to generate the repository layer.

6. Persisting Data and Finishing-Up Form Processing

Finally – let's implement the registration logic in our controller layer:

Example 6.1.1. – The RegisterAccount Method in the Controller

@PostMapping("/user/registration") public ModelAndView registerUserAccount( @ModelAttribute("user") @Valid UserDto userDto, HttpServletRequest request, Errors errors) { try { User registered = userService.registerNewUserAccount(userDto); } catch (UserAlreadyExistException uaeEx) { mav.addObject("message", "An account for that username/email already exists."); return mav; } return new ModelAndView("successRegister", "user", userDto); } 

Things to notice in the code above:

  1. The controller is returning a ModelAndView object which is the convenient class for sending model data (user) tied to the view.
  2. The controller will redirect to the registration form if there are any errors set at validation time.

7.The UserService – Register Operation

Let's finish the implementation of the registration operation in the UserService:

Example 7.1. The IUserService Interface

public interface IUserService { User registerNewUserAccount(UserDto userDto) throws UserAlreadyExistException; }

Example 7.2. – The UserService Class

@Service public class UserService implements IUserService { @Autowired private UserRepository repository; @Transactional @Override public User registerNewUserAccount(UserDto userDto) throws UserAlreadyExistException { if (emailExists(userDto.getEmail())) { throw new UserAlreadyExistException( "There is an account with that email address: + userDto.getEmail()); } User user = new User(); user.setFirstName(userDto.getFirstName()); user.setLastName(userDto.getLastName()); user.setPassword(userDto.getPassword()); user.setEmail(userDto.getEmail()); user.setRoles(Arrays.asList("ROLE_USER")); return repository.save(user); } private boolean emailExists(String email) { return userRepository.findByEmail(email) != null; } }

8. Loading User Details for Security Login

In our previous article, login was using hard coded credentials. Let's change that and use the newly registered user information and credentials. We'll implement a custom UserDetailsService to check the credentials for login from the persistence layer.

8.1. The Custom UserDetailsService

Let's start with the custom user details service implementation:

@Service @Transactional public class MyUserDetailsService implements UserDetailsService { @Autowired private UserRepository userRepository; // public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { User user = userRepository.findByEmail(email); if (user == null) { throw new UsernameNotFoundException( "No user found with username: "+ email); } boolean enabled = true; boolean accountNonExpired = true; boolean credentialsNonExpired = true; boolean accountNonLocked = true; return new org.springframework.security.core.userdetails.User (user.getEmail(), user.getPassword().toLowerCase(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(user.getRoles())); } private static List getAuthorities (List roles) { List authorities = new ArrayList(); for (String role : roles) { authorities.add(new SimpleGrantedAuthority(role)); } return authorities; } }

8.2. Enable the New Authentication Provider

To enable the new user service in the Spring Security configuration – we simply need to add a reference to the UserDetailsService inside the authentication-manager element and add the UserDetailsService bean:

Example 8.2.- The Authentication Manager and the UserDetailsService

Or, via Java configuration:

@Autowired private MyUserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); }

9. Conclusion

And we're done – a complete and almost production ready registration process implemented with Spring Security and Spring MVC. Next, we're going to discuss the process of activating the newly registered account by verifying the email of the new user.

The implementation of this Spring Security REST Tutorial can be found in the GitHub project – this is an Eclipse based project, so it should be easy to import and run as it is.

Next » Registration – Activate a New Account by Email « Previous Spring Security Registration Tutorial