SpringBoot Integrated Spring Security Getting Started Experience

Keywords: Programming Spring Shiro SpringBoot Java

1. Preface

Both Spring Security and Apache Shiro are security frameworks that provide authentication and authorization for Java applications.

The difference between them
  1. Spring Security: Heavy Safety Framework
  2. Apache Shiro: Lightweight Security Framework

Refer to another article in the subtitle on shiro's authorization and certification: SpringBoot Integrated Shiro Implements Dynamic Load Permissions

https://blog.csdn.net/qq_38225558/article/details/101616759

2. SpringBoot Integrated Spring Security Getting Started Experience

Basic environment: springboot 2.1.8

1. Introducing Spring Security dependencies

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

2. Create a new controller test access

@RestController
public class IndexController {
    @GetMapping("/index")
    public String index() {
        return "Hello World ~";
    }
}

3. Run Project Access http://127.0.0.1:8080/index

Warm Tip: Without any configuration, the default user name given by Spring Security, user password, is a string randomly generated by the project at startup time and will be printed to the console as follows: When we visit the index homepage, the system will jump to the login page by default for login authentication

Jump to our index page only after authentication is successful

3. Spring Security User Password Configuration

In addition to the user user user password given by default by Spring Security above without any configuration, which generates a random string with project startup, we can configure it as follows

1. Configuration in the springboot configuration file

spring:
  security:
    user:
      name: admin  # User name
      password: 123456  # Password

2. java code is configured in memory

New Security Core Configuration Class Inherits WebSecurityConfigurerAdapter

@Configuration
@EnableWebSecurity // Enable Web security support for Spring Security
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * Set user in memory
     * @param auth
     * @throws Exception
     */
    @Autowired
    public void config(AuthenticationManagerBuilder auth) throws Exception {
        // Configure users in memory, configure multiple users to invoke `and()`methods
        auth.inMemoryAuthentication()
                .passwordEncoder(passwordEncoder()) // Specify encryption
                .withUser("admin").password(passwordEncoder().encode("123456")).roles("ADMIN")
                .and()
                .withUser("test").password(passwordEncoder().encode("123456")).roles("USER");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        // Encryption tool provided by BCryptPasswordEncoder:Spring Security for fast encryption and salt addition
        return new BCryptPasswordEncoder();
    }

}

3. Get user account and password information from database

This is the way we normally use it in our projects, and I'll leave it for later articles.

4. Spring Security Logon Processing and Ignoring Interception

Relevant code has comments that are believed to be easy to understand

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * Logon Processing
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Turn on login configuration
        http.authorizeRequests()
                // Identity access `/index'This interface requires a `ADMIN` role
                .antMatchers("/index").hasRole("ADMIN")
                // Allow anonymous URLs - understandable as release interfaces - use of multiple interfaces, split
                .antMatchers("/", "/home").permitAll()
                // All remaining requests require authentication
                .anyRequest().authenticated()
                .and()
                // Set up login authentication page
                .formLogin().loginPage("/login")
                // Processing interface after successful login-Mode 1
                .loginProcessingUrl("/home")
                // Custom login username and password attribute names, defaulting to username and password
                .usernameParameter("username")
                .passwordParameter("password")
                // Processor after successful login - Mode 2
//                .successHandler((req, resp, authentication) -> {
//                    resp.setContentType("application/json;charset=utf-8");
//                    PrintWriter out = resp.getWriter();
//                    out.write("Sign in successfully...");
//                    out.flush();
//                })
                // Configure callbacks for login failures
                .failureHandler((req, resp, exception) -> {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write("Logon Failure...");
                    out.flush();
                })
                .permitAll()//All interfaces related to form login are directly accessed through
                .and()
                .logout().logoutUrl("/logout")
                // Configure callbacks that logged out successfully
                .logoutSuccessHandler((req, resp, authentication) -> {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write("Logoff successful...");
                    out.flush();
                })
                .permitAll()
                .and()
                .httpBasic()
                .and()
                // Turn off CSRF cross-domain
                .csrf().disable();

    }

    /**
     * Ignore Interception
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        // Set Intercept Ignore url - will filter the url directly - will not pass through the Spring Security filter chain
        web.ignoring().antMatchers("/getUserInfo");
        // Set Intercept Ignore Folder to allow access to static resources
        web.ignoring().antMatchers("/css/**", "/js/**");
    }

}

V. Summary

  1. Project Introducing Spring Security Dependencies
  2. Custom Security Core Configuration Class Inherits WebSecurityConfigurerAdapter
  3. Account Password Configuration
  4. Logon Processing
  5. Ignore Interception
Case demo source

https://gitee.com/zhengqingya/java-workspace

Posted by Plxply on Sun, 29 Sep 2019 23:50:21 -0700