3.springsecurity-store user data in the database

3.springsecurity-store user data in the database

table of Contents:

In real projects, in most cases, we design our own permission database. However, Spring Security also provides us with a permission database designed by itself. Let's take a look at what's going on first! Let's learn this simple first, and then we will look at the complex.


Spring Security supports a variety of different data sources. These different data sources will eventually be encapsulated into UserDetailsService instances. We can create a class to implement the UserDetailsService interface. In addition to encapsulating ourselves, we can also use the UserDetailsService instance provided by the system by default. , Such as the InMemoryUserDetailsManager introduced in the previous article and everyone.

Insert picture description here

In the last article, we used InMemoryUserDetailsManager to define the data source in memory; this time we use JdbcUserDetailsManager to allow us to connect the database and Spring Security through JDBC.


2.1 Database

JdbcUserDetailsManager itself provides a database model, which is stored in the following location:


Stored script:

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

As you can see, there is a data type varchar_ignorecase in the script, which is actually created for the HSQLDB database, and the MySQL we use does not support this data type, so you need to manually adjust the data type and change varchar_ignorecase to varchar. can.

After the modification is completed, create a database and execute the script after completion.

After executing the SQL script, we can see that a total of two tables have been created: users and authorities.

  • The users table saves basic user information, including user name, user password, and whether the account is available.
  • The roles of the user are stored in the authorities.
  • Authorities and users are related by username.
Insert picture description here

2.2 Configuration

    DataSource dataSource;
    protected UserDetailsService userDetailsService() {
        JdbcUserDetailsManager manager = new JdbcUserDetailsManager();
        if (!manager.userExists("javaboy")) {
        if (!manager.userExists("张三")) {
        return manager;

2.3 Dependence



2.4 Operation

Insert picture description here

Then you can use Zhang San to test login! ! !