Spring Security quick start

1 Introduction to spring security

Spring Security is a security framework that can provide declarative security access control solutions for spring based enterprise applications. As it is a member of the spring ecosystem, it is constantly revised and upgraded along with the whole spring ecosystem. It is very simple to add Spring Security to the spring boot project. Using Spring Security reduces the work of writing a large number of repeated codes for enterprise system security control.

2 create project

2.1 create maven project

Create maven project security spring security. The project structure is as follows:

2) Introduce the following dependencies:

Add spring security dependency on security spring MVC:

<dependencies>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>5.1.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>5.1.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>
    </dependencies>

2.2 Spring container configuration

Same as security spring MVC

/**
 * @author Administrator
 * @version 1.0
 **/
@Configuration //Equivalent to ApplicationContext xml
@ComponentScan(basePackages = "com.oldlu.security.springmvc"
            ,excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)})
public class ApplicationConfig {
    //Configure other beans besides Controller here, such as database link pool, transaction manager, business bean, etc.
}

2.3 Servlet Context configuration

Same as security spring MVC

/**
 * @author Administrator
 * @version 1.0
 **/
@Configuration//It is equivalent to spring MVC XML file
@EnableWebMvc
@ComponentScan(basePackages = "com.oldlu.security.springmvc"
        ,includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)})
public class WebConfig implements WebMvcConfigurer {


    //Video parser
    @Bean
    public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/view/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("redirect:/login");
    }

}

2.4 loading Spring container

Define the Spring container initialization class SpringApplicationInitializer under the init package, which implements the WebApplicationInitializer interface. When the Spring container starts, load all the implementation classes of the WebApplicationInitializer interface.

/**
 * @author Administrator
 * @version 1.0
 **/
public class SpringApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    //spring container, which is equivalent to loading ApplicationContext xml
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{ApplicationConfig.class, WebSecurityConfig.class};
    }

    //servletContext, which is equivalent to loading spring MVC xml
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    //url-mapping
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

3 certification

3.1 certification page

Spring security provides the authentication page by default, which does not require additional development, but it is not used in practice

3.2. Security configuration

spring security provides user name, password login, exit, session management and other authentication functions, which can be used only by configuration.

  1. Define websecurityconfig under the config package. The security configuration includes user information, password encoder and security interception mechanism.
/**
 * @author Administrator
 * @version 1.0
 **/
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    //Define user information service (query user information)
    @Bean
    public UserDetailsService userDetailsService(){
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("zhangsan").password("123").authorities("p1").build());
        manager.createUser(User.withUsername("lisi").password("456").authorities("p2").build());
        return manager;
    }

    //Cipher encoder
    @Bean
    public PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

    //Security interception mechanism (most important)
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/r/r1").hasAuthority("p1")
                .antMatchers("/r/r2").hasAuthority("p2")
                .antMatchers("/r/**").authenticated()//All / r / * * requests must be authenticated
                .anyRequest().permitAll()//In addition to / r / * *, other requests can be accessed
                .and()
                .formLogin()//Allow form login
                .successForwardUrl("/login-success");//Customize the page address of successful login

    }
}

In the userDetailsService() method, we return a UserDetailsService to the spring container, which Spring Security will use to obtain user information. For the time being, we use InMemoryUserDetailsManager to implement the class, create zhangsan and lisi users respectively, and set the password and permission.

In the configuration (), we set the security interception rules through HttpSecurity, which includes the following contents:

(1) Resources whose url matches / r / * * can only be accessed after authentication.

(2) Other URLs are fully open.

(3) Support form authentication, and turn to / login success after successful authentication.

For the configuration list of HttpSecurity, please refer to the appendix HttpSecurity.

  1. Load websecurityconfig

Modify the getrootconfigclasses () method of SpringApplicationInitializer and add websecurityconfig class:

 //spring container, which is equivalent to loading ApplicationContext xml
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{ApplicationConfig.class, WebSecurityConfig.class};
    }

3.2.Spring Security initialization

There are two situations for Spring Security initialization. If the current environment does not use spring or Spring MVC, you need to pass websecurityconfig (Spring Security configuration class) into the superclass to ensure that the configuration is obtained and the spring context is created. On the contrary, if spring is already used in the current environment, we should register Spring Security in the existing springContext (we have done in the previous step to load websecurityconfig into rootcontext). This method can do nothing. Define SpringSecurityApplicationInitializer under init package:

/**
 * @author Administrator
 * @version 1.0
 **/
public class SpringSecurityApplicationInitializer
        extends AbstractSecurityWebApplicationInitializer {
    public SpringSecurityApplicationInitializer() {
        //super(WebSecurityConfig.class);
    }
}

2.3. Default root path request

In webconfig Add the default request root path in Java and jump to / login. This url provides spring security with:

@Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("redirect:/login");
    }

spring security provides a login page by default.

2.4. Authentication success page

In the security configuration, if the authentication is successful, you will jump to / login success, and the code is as follows:

    @RequestMapping(value = "/login-success",produces = {"text/plain;charset=UTF-8"})
    public String loginSuccess(){
        return " Login successful";
    }

2.5 testing

(1) Start project, access http://localhost:8080/security -Spring security / path address

The page will jump to / login according to the configuration rules of addViewControllers in webconfig, / login is the login page provided by pring Security.

(2) Login

1. Enter the wrong user name and password

2. Enter the correct user name and password, and the login is successful

(3) Quit

1. Request / logout exit


2. After exiting, you can access the resources and automatically jump to the login page

4 authorization

To realize authorization, the user's access needs to be intercepted and verified to verify whether the user's permission can operate the specified resources. Spring Security provides authorization by default

Right realization method.

Add / r/r1 or / r/r2 in LoginController

 /**
     * Test resource 1
     * @return
     */
    @GetMapping(value = "/r/r1",produces = {"text/plain;charset=UTF-8"})
    public String r1(){
        return " Access resource 1";
    }

    /**
     * Test resource 2
     * @return
     */
    @GetMapping(value = "/r/r2",produces = {"text/plain;charset=UTF-8"})
    public String r2(){
        return " Access resource 2";
    }

In the security configuration class websecurityconfig Configure authorization rules in Java:

.antMatchers("/r/r1").hasAuthority("p1") .antMatchers("/r/r2").hasAuthority("p2")

.antMatchers("/r/r1").hasAuthority("p1") means that the url accessing the / R / R1 resource needs p1 permission.

.antMatchers("/r/r2").hasAuthority("p2") means that the url accessing the / R / r2 resource needs p2 permission.

The complete websecurityconfig method is as follows:

  //Security interception mechanism (most important)
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/r/r1").hasAuthority("p1")
                .antMatchers("/r/r2").hasAuthority("p2")
                .antMatchers("/r/**").authenticated()//All / r / * * requests must be authenticated
                .anyRequest().permitAll()//In addition to / r / * *, other requests can be accessed
                .and()
                .formLogin()//Allow form login
                .successForwardUrl("/login-success");//Customize the page address of successful login

    }

Test:

1. Login successful

2. Access / r/r1 and / r/r2. If you have permission, you can access normally. Otherwise, 403 (access denied) is returned

5 Summary

Through quick start, we use Spring Security to realize authentication and authorization. Spring Security provides authentication based on account and password. Through security configuration, we can realize request interception and authorization functions. Spring Security can accomplish more than that.

Keywords: Java Spring Spring Boot Spring Security

Added by kelesis on Mon, 07 Feb 2022 21:15:01 +0200