Proses Pendaftaran Dengan Keselamatan Musim Semi

Artikel ini adalah sebahagian daripada siri: • Tutorial Pendaftaran Keselamatan Musim Semi

• Proses Pendaftaran Dengan Spring Security (artikel terkini) • Pendaftaran - Aktifkan Akaun Baru melalui E-mel

• Pendaftaran Keselamatan Musim Semi - Hantar semula E-mel Pengesahan

• Pendaftaran dengan Spring Security - Pengekodan Kata Laluan

• API Pendaftaran menjadi RESTful

• Keselamatan Musim Semi - Tetapkan Semula Kata Laluan Anda

• Pendaftaran - Kekuatan dan Peraturan Kata Laluan

• Mengemas kini Kata Laluan anda

1. Gambaran keseluruhan

Dalam artikel ini, kami akan melaksanakan proses pendaftaran asas dengan Spring Security. Ini berdasarkan konsep yang diterokai dalam artikel sebelumnya, di mana kami melihat log masuk.

Tujuannya di sini adalah untuk menambahkan proses pendaftaran penuh yang membolehkan pengguna mendaftar, mengesahkan dan mengekalkan data pengguna.

2. Halaman Pendaftaran

Pertama - mari kita laksanakan halaman pendaftaran mudah yang memaparkan bidang berikut :

  • nama ( nama pertama dan belakang)
  • e-mel
  • kata laluan (dan medan pengesahan kata laluan)

Contoh berikut menunjukkan halaman pendaftaran.html mudah :

Contoh 2.1.

form

first

Validation error

last

Validation error

email

Validation error

password

Validation error

confirm submit login

3. Objek DTO Pengguna

Kami memerlukan Objek Pemindahan Data untuk menghantar semua maklumat pendaftaran ke backend Spring kami. The DTO objek harus mempunyai semua maklumat yang kita akan memerlukan kemudian apabila 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 bahawa kami menggunakan anotasi javax.validation standard pada medan objek DTO. Kemudian, kami juga akan menerapkan anotasi pengesahan tersuai untuk mengesahkan format alamat e-mel dan juga untuk pengesahan kata laluan. (lihat Bahagian 5)

4. Pengawal Pendaftaran

A Sign-Up link di login page akan membawa pengguna kepada pendaftaran halaman. Bahagian belakang halaman ini tinggal di pengawal pendaftaran dan dipetakan ke "/ pengguna / pendaftaran" :

Contoh 4.1. - Kaedah pertunjukan

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

Apabila pengawal menerima permintaan "/ pengguna / pendaftaran" , ia membuat objek UserDto baru yang akan menyokong borang pendaftaran , mengikatnya dan kembali - cukup mudah.

5. Mengesahkan Data Pendaftaran

Seterusnya - mari kita lihat pengesahan yang akan dilakukan pengawal semasa mendaftarkan akaun baru:

  1. Semua medan yang diperlukan diisi (Tiada medan kosong atau kosong)
  2. Alamat e-mel adalah sah (dibentuk dengan baik)
  3. Medan pengesahan kata laluan sepadan dengan medan kata laluan
  4. Akaun belum ada

5.1. Pengesahan Terbina Dalam

Untuk pemeriksaan ringkas, kami akan menggunakan anotasi pengesahan kacang di luar objek pada objek DTO - anotasi seperti @NotNull , @NotEmpty , dll.

Untuk mencetuskan proses pengesahan, kami hanya akan memberi penjelasan pada objek di lapisan pengawal dengan penjelasan @Valid :

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

5.2. Pengesahan Tersuai untuk Memeriksa Kesahan E-mel

Seterusnya - mari kita sahkan alamat e-mel dan pastikan alamatnya dibentuk dengan baik. Kami akan membina validator khusus untuk itu, serta anotasi pengesahan tersuai - mari kita panggil bahawa @ValidEmail .

Sidenote cepat di sini - kami melancarkan anotasi tersuai kami sendiri dan bukannya Hibernate @Email kerana Hibernate menganggap format alamat intranet lama: [dilindungi e-mel] sebagai sah (lihat artikel Stackoverflow), yang tidak bagus.

Berikut adalah anotasi pengesahan e-mel dan pengesah tersuai:

Contoh 5.2.1. - Anotasi Khusus untuk Pengesahan E-mel

@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 bahawa kami telah menentukan anotasi pada tahap FIELD - kerana di situlah ia berlaku secara konseptual.

Contoh 5.2.2. - Email Custom Validato :

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(); } }

Mari sekarang gunakan anotasi baru pada pelaksanaan UserDto kami :

@ValidEmail @NotNull @NotEmpty private String email;

5.3. Menggunakan Pengesahan Khusus untuk Pengesahan Kata Laluan

Kami juga memerlukan anotasi dan validator khusus untuk memastikan bahawa kata laluan dan medan Kata Laluan yang sepadan:

Contoh 5.3.1. - Anotasi Khusus untuk Mengesahkan Pengesahan Kata Laluan

@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