Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

Writing in the front

To undertake the above, the above mentioned configuration system, today mainly explains the certification system. If you are interested, click on your profile picture to view my column and historical articles.

Spring Security user authentication system

Back to the user authentication scenario. Because Spring Security provides fixed user names by default and passwords that change with each application launch, it is inflexible. In Spring Boot.

We can change this default behavior by adding the following configuration items to the application.yml configuration file:

spring:
  security:
    user:
      name: spring
      password: spring_password
Copy the code

We can log in using the above username and password. The configuration file-based user information storage solution is simple and straightforward, but it is also obviously inflexible because we cannot dynamically load the corresponding user name and password while the system is running.

Therefore, in reality, we mainly through the use of WebSecurityConfigurerAdapter configuration class to change the default configuration.

The previous said, we know that can configure WebSecurityConfigurerAdapter class (HttpSecurity HTTP) method to complete the certification.

The authentication process involves the interaction of user information in Spring Security, We can through inheritance WebSecurityConfigurerAdapter class and overwrite the configure (AuthenticationManagerBuilder auth) method to complete the configuration of the user information. Note that these are two different configure() methods.

Two kinds of schemes

For the WebSecurityConfigurer configuration class, we first need to clarify what is configured. In fact, initializing user information is as simple as specifying a Username, Password, and Role. In Spring Security, based on AuthenticationManagerBuilder tools provides developers with memory, JDBC, LDAP authentication scheme.

Next, we’ll around AuthenticationManagerBuilder provides functions to achieve a variety of user information storage solution.

Memory – based user information storage scheme

Implementation method is invoked AuthenticationManagerBuilder inMemoryAuthentication method, the example code is as follows:

@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
 
    builder.inMemoryAuthentication()
        .withUser("spring_user").password("password1").roles("USER")
        .and()
        .withUser("spring_admin").password("password2").roles("USER"."ADMIN");
}
Copy the code

From the above code, we can see that there are two users “spring_user” and “spring_admin” in the system. Their passwords are “password1” and “password2” respectively. They also represent the common USER and administrator ADMIN respectively.

Note that the ROLES () method here still uses the authorities() method behind it. Spring Security automatically prefixes each role name with “ROLE_” through the roles() method, so we can do the same with code like this:

@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
 
    builder.inMemoryAuthentication()
         .withUser("spring_user").password("password1").authorities("ROLE_USER")
         .and()
         .withUser("spring_admin").password("password2").authorities("ROLE_USER"."ROLE_ADMIN");
}
Copy the code

As you can see, the memory-based user information storage scheme is also relatively simple to implement, but it is also inflexible because the user information is written in code. So, let’s move on to another, more common storage scheme for user information — database storage.

Database – based user information storage scheme

Since you are storing user information in a database, you need to create a table structure. We can in the Spring Security source file (org/springframework/Security/core/populated userdetails/JDBC/users. The DDL) found in the corresponding SQL statement, as shown below:

create table users(username varchar_ignorecase(50) not null primary key,password varchar_ignorecase(500) not null,enabled boolean not null);
 
create table authorities (username varchar_ignorecase(50) not null,authority varchar_ignorecase(50) not null,constraint fk_authorities_users foreign key(username) references users(username));
 
create unique index ix_auth_username on authorities (username,authority);
Copy the code

Once we have created the two tables in our own database and added the corresponding data, we can query the user data directly by injecting a DataSource object as follows:

@Autowired
DataSource dataSource;
 
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
 
        auth.jdbcAuthentication().dataSource(dataSource)
               .usersByUsernameQuery("select username, password, enabled from Users " + "where username=?")
               .authoritiesByUsernameQuery("select username, authority from UserAuthorities " + "where username=?")
               .passwordEncoder(new BCryptPasswordEncoder());
}
Copy the code

Here using the AuthenticationManagerBuilder jdbcAuthentication authentication methods to configure database, internal use JdbcUserDetailsManager this utility class. In this class, various SQL statements for database queries are defined, as well as the implementation method of database access using JdbcTemplate.

Please note that we are using a passwordEncoder() method, which is a password decrypter provided in Spring Security. We will use the “Password Security: What encryption and decryption technologies are included in Spring Security?” method in the “Password Security: What encryption and decryption technologies are included in Spring Security? This will be discussed in detail in lecture 1.

conclusion

In two articles, I introduced a systematic approach to building a user authentication system using Spring Security.

In Spring Security, authentication related functions can be customized and managed through configuration architecture. With a simple configuration approach, we can use a combination of HTTP base authentication and form login authentication, as well as in-memory and database-based solutions to store user information, which are built into Spring Security.

We will continue our in-depth understanding in the next article. We welcome your comments and study together

overtones

Thank you for reading, if you feel that you have learned something, please like, follow. Also welcome to have a question we comment below exchange

Come on! See you next time!

To share with you a few I wrote in front of a few SAO operation

Talk about different strategy patterns (Bookmarks)

Copy object, this operation is a little SAO!