Take a minute to learn about Spring Security!

Keywords: Java Spring SpringBoot Mybatis

1. What is Spring Security?

Spring Security is a powerful and highly customizable authentication and access control framework that is the de facto standard used to protect Spring-based applications.

Spring Security is a framework for providing authentication and authorization for Java applications.As with all Spring projects, the real power of Spring Security is that it can be easily extended to meet custom requirements.

More information can be found on the official website: https://spring.io/projects/spring-security

2. Main functions of Spring Security

  • Authentication: Verify that the user name and password are legitimate (users in the system)
  • Authorization: Being a system user does not mean you can use certain features because you may not have permissions
  • Defense against fixed sessions, hijacking, cross-site requests for forgery, and other attacks
  • Servlet API Integration
  • Optional integration with Spring Web MVC

3. Quick Start

Create a new SpringBoot web project, spring-boot-security.

Case 1: Interface does not add protection

Spring Security is not introduced in the pom file, and a new controller is created:

@RestController
public class AppController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello,spring security!";
    }
}

Then open the browser to access: http://localhost:8080/hello and return to:

Hello,spring security!

Case 2: Interface Add Protection

  1. pom file add dependency

starter of Spring Security is introduced into the pom file:

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

Opening the browser and accessing http://localhost:8080/hello again will redirect it to the login page http://localhost:8080/login, as shown below:

To log in to the system, we need to know the user name and password. The default user name for Spring Security is user. The default password (visible in the startup log) is generated when the project starts. After entering the user name and password, you can access the / hello interface.

You can also customize your username password by adding the following to your profile:

spring.security.user.name=java_suisui
spring.security.user.password=123456

4. Custom Authentication and Authorization

As mentioned above, Spring Security features Authentication and Authorization. Here is a simple example to implement custom authentication and authorization.

Suppose there are two roles in the system:

  • ADMIN can access resources under/admin
  • USER can access resources under / user

Follow the steps below.

  1. Create a new configuration class

User names, passwords, login pages, access rights, and so on can be configured in the implementation class of the WebSecurityConfigurerAdapter.

The WebSecurityConfig code is as follows:

/**
 * Configuration Class
 * @Author java_suisui
 *
 */
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //Configure in-memory user names, passwords, and roles
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("user").password("123456").roles("USER");
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("admin").password("123456").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/login").permitAll()
                .antMatchers("/user").hasRole("USER") //Accessing/user interface requires USER role
                .antMatchers("/admin").hasRole("ADMIN")
                .anyRequest().authenticated() //Other interfaces remaining, accessible after login
                .and()
                .formLogin().defaultSuccessUrl("/hello");
    }
}
  1. Create implementation class for PasswordEncorder

When validating memory users, the security dependency referenced by Spring Boot versions above 2.0 is spring Security version 5.X, which requires an instance of PasswordEncorder.

The MyPasswordEncoder code is as follows:

public class MyPasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence rawPassword) {
        return rawPassword.toString();
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return encodedPassword.equals(rawPassword);
    }
}
  1. validate logon

The browser opens http://localhost:8080/login,

  • Use user login to access/user
  • Use admin login to access/admin

If you use user login to access/admin, a 403 error will be reported with the following error information:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue Nov 19 16:26:28 CST 2019
There was an unexpected error (type=Forbidden, status=403).
Forbidden

The results are consistent with our expectations, indicating that simple custom authentication and authorization functions have been implemented.

Full source address: https://github.com/suisui2019/springboot-study

Recommended reading

1.1 minute to learn how to use mybatis-generator to automatically generate code!

2. Hand-held Seven Transaction Dissemination Behaviors of Spring in Practice

3.SpringBoot Series - Integrated Mybatis

4.SpringBoot Series - Integrate Mybatis (XML Configuration)

5. Print logs in Java, these 4 points are important!

Java Fragmentation, an original public name, provides you with a series of high-quality technical articles on system architecture, micro-services, Java, SpringBoot, SpringCloud, etc.
If you think the article is good, I hope you can forward it anywhere or "look at it" oh, thanks a lot!
Respond to "1024" after following the public number. It's amazing!

This article is published by blog OpenWrite Release!

Posted by g00fy_m on Tue, 19 Nov 2019 17:44:11 -0800