Many people find it difficult to implement login authentication in Spring Security, and I felt that way when I first started learning. Because I haven’t understood how to combine the Controller I wrote for receiving user names and passwords with Spring Security for a long time, this is a preconceived mistake. Then I figured it out: you don’t have to write controllers yourself. All you need to tell Spring Security is what is the user information, role information, permission information, and login page? What is the login success page? Or anything else about logging in. Specific login authentication logic it will help you achieve.

First, the basic knowledge of dynamic data login authentication

In previous articles, Spring Security’s formLogin login authentication mode, RBAC’s permission control management model, and source code for Spring Security’s login authentication logic have been analyzed. All of our user, role, and permission information is written to death in configuration files, whereas in real business systems, this information is usually stored in database tables in the RBAC permission model. Let’s review the core concepts:

  • RBAC’s permission model can obtain one or more roles assigned to users from users, and obtain multiple permissions for that role from users’ roles. You can obtain the role and permission information of a user through associated query.
  • In the source code parsing article, we learned that if we don’t want user, role, and permission information written in the configuration. We should implement the UserDetails and UserDetailsService interfaces to dynamically load the information from a database or other store.

This is a summary of some of the core basics. If you are not clear about them, you are advised to read on. If you still have difficulty understanding this article, I suggest you read the article before this number.

2. Interface between UserDetails and UserDetailsService

  • The UserDetailsService interface has a method called loadUserByUsername, which is used to dynamically load user, role, and permission information. The function is known by name: loads users by username. The return value of this method is UserDetails.
  • UserDetails is the user name, password, and permissions of the user.

Let’s take a look at the methods of the UserDetails interface.

Public interface UserDetails extends Serializable {// Obtain user permission Collection<? extends GrantedAuthority> getAuthorities(); String getPassword(); String getUsername(); // Whether the account has not expired Boolean isAccountNonExpired(); // Whether the account is not locked Boolean isAccountNonLocked(); // Whether the password is valid Boolean isCredentialsNonExpired(); // Whether the account is available Boolean isEnabled(); }Copy the code

Now, we understand that once we provide this information to Spring Security, Spring Security will know how to do login authentication without having to write our own Controller to implement login authentication logic.

3. Implement the UserDetails interface

public class SysUser implements UserDetails{ String password(); // Password String username(); // Username Boolean accountNonExpired; Boolean accountNonLocked; Boolean credentialsNonExpired; Boolean enabled; // Can the account be Collection<? extends GrantedAuthority> authorities; // Omit the constructor // omit the set method // omit the get method (i.e. the method of the interface UserDetails)}Copy the code

We simply wrote a Java POJO class for UserDetails. The implementation of the UserDetails interface is a set of GET methods. The get method is called by Spring Security, and we provide Spring Security with the UserDetails data through the set method or constructor.

Implement the UserDetailsService interface

@Component public class MyUserDetailsService implements UserDetailsService{ @Override public UserDetails LoadUserByUsername (String username) throws UsernameNotFoundException {/ / here sys_user table from a database query entity class object inside. The loadUser method can be self-implemented using Mybatis or JDBC or JPA. SysUser sysUser = loadUser(username); / / determine whether a user exists the if (user = = null) {throw new UsernameNotFoundException (" the user name does not exist "); } // From the database all ROLE information, all permission flags // traverses all roles and all Authority permissions (menu, button). // Separate their unique identifiers with commas, and the process takes care of itself. sysUser.setAuthorities( AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_AMIN , system:user:delete")); / / sysUser setAccountNonLocked (true or false); return sysUser; }}Copy the code

  • Generally, the sys_USER field of the database table must correspond to the SysUser attribute one by one, such as username, password, and enabled. But for example, the accountNonLocked field is used for multiple false locks on a login, but we typically don’t store a lock in the table, we store a lock time field in the table. The lock time is longer than the current time to determine whether the account is locked, so in the process of implementation can be flexible to make judgment and good set method, do not stick to the form of one-to-one correspondence.
  • A role is a special privilege. In Spring Security, we can use hasRole expressions to determine whether a user has a role and can perform an action. The hasAuthority expression is used to determine whether an operation has permission.

5. Final remarks

At this point, Spring Security is informed of all user, role, and permission information in the system through UserDetailsService and UserDetails. But most of your friends probably still don’t know how to implement the login function, in fact, the rest of the matter is very simple:

  • Write a login screen, write a login form, and submit the form to the default /login path using the POST method
  • The default username and password fields are username and password.
  • Write a successful login to the jump page, such as index.html

This information is then communicated to Spring Security through a configuration that can be modified. If you do not know how to configure this please refer to the previous article “formLogin Login Authentication Mode”.

We look forward to your attention

  • I recommend the blogger’s series of documents: “Hand on Hand to teach you to learn SpringBoot Series – Chapter 16, Section 97”.
  • This article is reprinted with a credit (must be accompanied by a link, not only the text) : Antetokounmpo blog.