SpringSecurity - SpringBoot basic configuration

The basic configuration of SpringSecurity

SpringBoot for SpringSecurity provides automated configuration options, so you can make SpringSecurity very easily integrated into SpringBoot project, which is using SpringSecurity advantage SpringBoot project.

Basic Usage

1. Create a project, add dependencies:

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

2. Add hello Interface:

@RestController
public class HelloController {

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

3. Start project testing:
Access / hello interfaces will automatically jump to the login page, the login page is provided by SpringSecutiry of:
Here Insert Picture Description

The default user name is user, the default password is randomly generated each time the project started:
Here Insert Picture Description

Configuring user name and password

You can configure the default user name application.properties, the password and user roles:

spring.security.user.name=sang
spring.security.user.password=123
spring.security.user.roles=admin

When the developer to configure the default user name and password application.properties, start the project again, start logging project will not print out a randomly generated password, users can directly use the configured user name and password, the login is successful The user also has a role --admin.

Memory-based authentication

Developers can also customize the class inherits from WebSecurityConfigurerAdapter , thus achieving more SpringSecurity custom configuration, for example, memory-based authentication, arranged as follows:

//自定义MyWebSecurityConfig继承WebSecurityConfigurerAdapter
@Configuration
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
    
    //指定不对密码进行加密
    @Bean
    PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

    /*
        重写configure(AuthenticationManagerBuilder auth)
            配置两个用户:
                1. 用户名:admin,密码:123,角色:ADMIN和USER
                2. 用户名:sang,密码:123,角色:USER
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("123").roles("ADMIN", "USER")
                .and()
                .withUser("sang").password("123").roles("USER");
    }
}

After configuration is complete, restart the project, you can use two user configurable here to sign up.

HttpSecurity

Although you can now implement authentication, but protected resources are the default, and can not be the role of management in accordance with the actual situation, if you want to implement these features, it is another method WebSecurityConfigurerAdapter the need to rewrite:

@Configuration
public class MyWebSecurityConfig2 extends WebSecurityConfigurerAdapter {
    
    @Bean
    PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }
    
    
    /*
    配置三个用户:
          1. root用户具备ADMIN和DBA角色
          2. admin具备ADMIN和USER角色
          3. sang具备USER角色
    */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("root").password("123").roles("ADMIN", "DBA")
                .and()
                .withUser("admin").password("123").roles("ADMIN", "USER")
                .and()
                .withUser("sang").password("123").roles("USER");
    }

    
    /*
        1. 用户访问"/admin/**"必须具备ADMIN角色
        2. 用户访问"/user/**"必须具备ADMIN或者USER角色
        3. 用户访问"/db/**"必须具备ADMIN和DBA的角色
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //开启HttpSecurity的配置
        http.authorizeRequests()
                .antMatchers("/admin/**")
                .hasRole("ADMIN")
                .antMatchers("/user/**")
                .access("hasAnyRole('ADMIN', 'USER')")
                .antMatchers("/db/**")
                .access("hasRole('ADMIN') and hasRole('DBA')")
                .anyRequest()//除了前面定义的URL模式之外,用户访问其它的URL都必须认证后访问
                .authenticated()
                .and()
                .formLogin()//开启表单登录,配置登录接口为"/login",可以直接调用"/login"接口,发起一个POST请求进行登录,参数中用户名必须为username,密码必须为password
                .loginProcessingUrl("/login")
                .permitAll()//和登录相关的接口都不要认证即可访问
                .and()
                .csrf()//关闭csrf
                .disable();
    }
}

Add the following interface test Controller:

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello(){
        return "Hello";
    }
    
    @GetMapping("/admin/hello")
    public String admin(){
        return "hello admin!";
    }
    
    @GetMapping("/user/hello")
    public String user(){
        return "hello user!";
    }
    
    @GetMapping("/db/hello")
    public String dba(){
        return "hello dba!";
    }
}

Test Results:

  • "/ Admin / hello" Interface: root and admin users have access
  • "/ User / hello" Interface: admin and sang user has access
  • "/ Db / hello" Interface: Only the root user has access
Published 698 original articles · won praise 2032 · Views 250,000 +

Guess you like

Origin blog.csdn.net/cold___play/article/details/104215643