SoFunction
Updated on 2025-04-07

Spring Security's persistent user and authorization implementation method

Use JdbcUserDetailsManager (another implementation of UserDetailsService) to implement database reading users

1.Introduce jdbc and related database drivers

<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId></groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
</dependency>

2. Create a database table

--User table
CREATE TABLE users( 
    username VARCHAR(50)  NOT NULL PRIMARY KEY --username, 
    password VARCHAR(500) NOT NULL             --password, 
    enabled  BOOLEAN      NOT NULL             --Effectiveness
);
--Permission table
CREATE TABLE authorities( 
    username  VARCHAR(50) NOT NULL  --username, 
    authority VARCHAR(50) NOT NULL  --Permissions, 
    constraint fk FOREIGN KEY(username) REFERENCES users(username)
);
CREATE unique index ix_auth_username ON authorities (username, authority);

3. Configure database connection ()

spring:
    datasource:
        driver-class-name: 
        url: jdbc:postgresql://localhost:5432/security
        username:postgres
        password: postgres

4. Modify SecurityConfig configuration

@Configuration
public class SecurityConfig {
    //Configure Security filter chain    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        //Configure which interfaces need authentication (.anyRequest().authenticated() means that any request needs authentication)        (authorize -&gt; {
            ().authenticated();
        });
        //Configure post form request/login interface        (());
        //Csrf attack: The development environment is not suitable for convenient debugging, and the online environment needs to be configured, otherwise it will be attacked by Csrf        (AbstractHttpConfigurer::disable);
        //Return Security filter chain object        return ();
    }

    @Bean //Configure JdbcUserDetailsManager to implement database storage user    public UserDetailsService userDetailsService(DataSource dataSource) {
        return new JdbcUserDetailsManager(dataSource);
    }
}

Implement Spring Security Authorization Function

1. Create an interface

@RestController
public class HelloController{

    @RequestMapping("/hello")
    public String hello() { 
        return "Hello Security"; 
    }

    @RequestMapping("/hello1")
    public String hello1() { 
        return "Hello Security1"; 
    }

}

2. Configure database account and permissions (DbUser users have hello and hello1 permissions, DbUser1 only has hello1 permissions)

3. Modify SecurityConfig configuration

@Configuration
public class SecurityConfig {
    //Configure Security filter chain    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        //Configure which interfaces need authentication (.anyRequest().authenticated() means that any request needs authentication)        (authorize -&gt; {
            ("/hello").hasAuthority("hello");
            ("/hello1").hasAuthority("hello1");
            ().authenticated();
        });
        //Configure post form request/login interface        (());
        //Csrf attack: The development environment is not suitable for convenient debugging, and the online environment needs to be configured, otherwise it will be attacked by Csrf        (AbstractHttpConfigurer::disable);
        //Return Security filter chain object        return ();
    }

    @Bean //Configure JdbcUserDetailsManager to implement database storage user    public UserDetailsService userDetailsService(DataSource dataSource) {
        return new JdbcUserDetailsManager(dataSource);
    }
}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.