Define users in the database

Previously we defined the user as the default user defined in the configuration file and code. This is not usually done in development. Our users are all from our user table, stored in the database. There are many techniques for manipulating databases, and Spring Security supports a JDBC approach by default, which is used to query users from the database. First define the user table users:

The enabled field indicates whether the user is enabled. If the value is 0, the user is not allowed to log in. Add two users to the table:

Note that {noop} is added to the front of the password, which is the default encryption algorithm for JDBC query. In fact, this approach requires several tables to be defined, and here we demonstrate that defining a Users user table is sufficient.

Add the dependent

Since we are added to the database, we will add two dependencies:

The data source can be configured as springBoot:

Configure a JDBC

Delete the memory user defined in the configuration class and add a Bean to the configuration class:

This is fully configured to use JDBC to query the user from the database, and the startup can be logged in as admin/admin and user/123456.

instructions

This JDBC configuration is simple, but there are a lot of definitions, such as the representation and the three fields in the table, that can be changed.

The above configuration class uses the JdbcUserDetailsManager class. Let’s enter this class and have a look at the contents:

As you can see, there are a lot of default SQL statements in the table, which explains why the user table is called user, and why the above three fields are defined, adding, deleting, and checking which statements the user has executed. In addition, the default statement not only has the Users table, but also has the groups table, the authorities table, and some other tables, which can be seen from the structure of the entire permission system. We can modify the default statement by calling the corresponding set method:

But even though all of this can be configured, it is too rigid for real business, especially for slightly larger projects where the customization of the permissions system is a big part of the design, so this JDBC approach is not very adaptable. The more practical Mybatis approach will be introduced later.

07 code address: https://gitee.com/blueses/spring-boot-security