SoFunction
Updated on 2025-03-09

Simple way to use spring-boot-starter-security

Use security based on configuration files

First introduce two necessary dependencies

        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

Since springboot automatically configures the starter dependency, that is, the agreement is greater than the configuration, that is, when the dependency with starter is integrated, when we do not make any configuration, the configuration agreed by the starter is used by default. Only when we make custom configurations, springboot will use our configuration

Configure a user in memory through configuration files

spring:
  application:
    name: spring-security
  security:
    user:
      name: user
      roles: admin
      password: 123456
server:
  port: 8848

Since spring-boot-starter-security enables login authentication by default, we need to create a new controller class of TestController

@RestController
@RequestMapping("/test")
public class TestConteoller {

    @GetMapping("/security")
    public String security(){
        return "Test-spring-security login successfully";
    }
}

Start the application and visit http://localhost:8848/test/security. We will see the login page that comes with spring-boot-starter-security. Enter the user name and password we configured in the configuration file. After that, we will see it on the page.

Test-spring-security login successfully

Use security based on configuration classes

Above we implemented a simple security configuration based on configuration files. Obviously, this is not applicable to real-life scenarios. Let's see below to implement the custom configuration of security through configuration classes.

Create a new config folder and create a SecurityConfig configuration class in it, let it inherit the WebSecurityConfigurerAdapter abstract class and override two configuration methods to implement the security custom configuration in the web environment.

The details are as follows:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //Customize the permission control of URL resources    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
                //Authentication of permissions for all requests                authorizeRequests()
                //Custom configuration request address permission                .mvcMatchers("/test/security").permitAll()
                // permitAll() releases all requests                .mvcMatchers("/admin/security").hasRole("admin")
                .mvcMatchers("/user/security").hasRole("user")
                .mvcMatchers("/tUser/selectAll").anonymous()
                // anonymous() allows anonymous access, login status cannot be accessed
                .anyRequest().authenticated()       //All requests require authentication                .and()
                .formLogin()
                //.loginPage("login") Custom login page                .permitAll()        //All users can access                .and()
                .logout()
                //.logoutUrl("logout") Custom configuration logout page                .permitAll();
    }


    //Customize configuration authentication rules    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //Spring has two built-in UserDetailManager implementations, one is the memory-based InMemoryUserDetailsManager, and the other is the database-based JdbcUserDetailsManager
        auth.
                //Use InMemoryUserDetailsManager in memory (memory user manager)                inMemoryAuthentication()
                //Do not use passwordEncoder password encryption                .passwordEncoder(())
                //Configure user in memory                .withUser("admin").password("admin").roles("admin")
                .and()
                //Configure admin user in memory                .withUser("user").password("user").roles("user");

    }
}

After the security configuration class is completed, we create two interface test classes: UserController and AdminController

The details are as follows:

@RestController
@RequestMapping("/user")
public class UserController {

    
    @GetMapping("/security")
    public String security(){
        return "user-spring-security login successfully";
    }
}


@RestController
@RequestMapping("/admin")
public class AdminController {

 
    @GetMapping("/security")
    public String security(){
        return "Admin-spring-security login successfully";
    }
}

Restart the application and access three addresses: http://localhost/test/security, http://localhost/user/security, and http://localhost/admin/security. We will find that the first address can be accessed directly without logging in. The second address requires user role permissions, and the third address requires admin role permissions;

It should be noted that when we access the second address and log in with the user role, we will report a 403 error when we access the third address. The reason is that the browser caches the user's login session information, i.e. the session status, when we log in with the user's login status. Therefore, when we log in to the third address, the browser will access the interface under the admin role with the user's login status. Obviously, this cannot be accessed.

Implement permission authentication of methods in interfaces based on annotation

First add @EnableGlobalMethodSecurity(prePostEnabled = true) in the SecurityConfig configuration class to enable this function

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)      //Enable method-based annotation permission authentication, default is falsepublic class SecurityConfig extends WebSecurityConfigurerAdapter {

Then we can use @PreAuthorize("hasAuthority('ROLE_user')") or @PreAuthorize("hasRole('user')") to perform the corresponding permission verification on the method we want to perform permission verification.

Special Note:

There is basically no difference between hasRole and hasAuthority. The main difference is that hasRole will add ROLE_ prefix before the role name we added, so the permission string in the database needs to be prefixed with ROLE_ prefixed.

That is, if the user role stored in the database is ROLE_admin, here is admin. hasAuthority is the same as the database

Summarize

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