The origin of spring boot integrating spring security (zero)

Time:2020-4-22

The origin of spring boot integrating spring security (zero)

The origin of spring boot integrating spring security (zero)

This is the first article of spring security. It mainly introduces what spring security is and how to use it in springboot

<!– more –>

1. Basic knowledge points

Official document: https://docs.spring.io/spring-security/site/docs/5.2.2.build-snapshot/reference/htmlsingle/ ා community help

Here is the official introduction

Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.

Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements

In Mandarin, let’s talk about its definition in a simple and abstract way

  • Very authentication and access rights verification framework

So what can I do?

  • User login authentication: user name + password login to determine user identity
  • User access authentication (common ACL access control list, RBAC role access control): determine whether you have access to a resource
  • Security (CSRF cross site attack, session fixation attack…)

2. Initial experience

Let’s see how to use spring security in spring boot

1. Configuration

First, you need to add the spring boot project, and then add the security dependency. The relatively complete POM configuration is as follows (note that the version of spring boot we use is 2.2.1. Release)

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<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>
</dependencies>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </pluginManagement>
</build>
<repositories>
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/libs-snapshot-local</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/libs-milestone-local</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-releases</id>
        <name>Spring Releases</name>
        <url>https://repo.spring.io/libs-release-local</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

2. Instance demo

After the above configuration, there is no need to do anything. The project has been connected to spring security. The services in the project need to be logged in before they can be accessed

//Program start class
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

//Rest Service
@RestController
public class IndexRest {

    @GetMapping(path = {"/", "/index"})
    public String index() {
        return "hello this is index!";
    }

    @GetMapping(path = "hello")
    public String hello(String name) {
        return "welcome " + name;
    }
}

When we need to visit the homepage, we will find that direct 302 redirects to the login page, as shown below

The origin of spring boot integrating spring security (zero)

By default, spring security generates a log with the user name as user and the password as output from the consoleUsing generated security password: aa410186-5c04-4282-b217-507ffb1f61eb

After login, we will redirect back to the URL we visited before. You can see through packet capturing. After login, we will set the cookie of the requester, and the subsequent requests will carry the cookie to indicate the user’s identity

The origin of spring boot integrating spring security (zero)

3. Basic configuration

Although an initial experience project of Hello world is demonstrated above, the default user name / password is a little ghostly. The default configuration mainly comes fromorg.springframework.boot.autoconfigure.security.SecurityProperties.User, here is a screenshot (so the user name in front is user)

The origin of spring boot integrating spring security (zero)

Next we need to configure the configuration file for the project in a human friendly wayapplication.yml, specify the login user name / password

spring:
  security:
    user:
      name: yihuihui
      password: 123456

Restart the test project and use the new user name / password (yihuihui / 123456) to log in successfully;

4. User identity acquisition

Although the above is a simple case, I have to mention that in my interface, although I know you are logged in, how do I know who you are?

We can go straight throughHttpServletRequest#getRemoteUser()To get the logged in user; orSecurityContextHolder.getContext().getAuthentication().getPrincipal()To get authorization information

Let’s write a general method

public String getUser() {
    return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getRemoteUser();
}

// or
public Object getUser() {
    SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}

Then change our service interface a little

@GetMapping(path = {"/", "/index"})
public String index() {
    return "hello this is index! welcome " + getUser();
}

After another visit, the results are as follows

The origin of spring boot integrating spring security (zero)

5. Summary

This article is mainly about the origin of spring security series. The first section introduces what spring security is and what features it has

  • Spring security is a very authentication (can be simply understood as login authentication) and authentication (can be simply understood as access control) framework
  • Three features: login + authentication + security protection

The second section introduces a simple example of HelloWorld

  • Springboot project, adding dependenciesspring-boot-starter-security; all HTTP interface accesses need to be logged in. By default, a UUID string with user name and password output from the console is provided
  • adoptspring.security.user.nameandspring.security.user.passwordTo specify the user name and password
  • adoptHttpServletRequest#getRemoteUser()Get login user

So the question is, what system may have only one user? What about multiple users? What about different users and different permissions? What about some interfaces that everyone can access?

2. Others

0. Project

  • Project: https://github.com/liuyueyi/spring-boot-demo
  • Code: https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-security/000-basic-demo

1. A grey blog

The best letter is not as good as the above. It’s just a one-of-a-kind remark. Due to the limited personal ability, there are inevitably omissions and mistakes. If you find a bug or have better suggestions, you are welcome to criticize and correct. Thank you very much

Here is a grey personal blog, recording all the blogs in study and work. Welcome to visit

  • One gray blog https://blog.hhui.top
  • Http://spring.hhui.top

The origin of spring boot integrating spring security (zero)

Recommended Today

The use of springboot Ajax

Ajax overview What is Ajax? data Ajax application scenarios? project Commodity system. Evaluation system. Map system. ….. Ajax can only send and retrieve the necessary data to the server, and use JavaScript to process the response from the server on the client side. data But Ajax technology also has disadvantages, the biggest disadvantage is that […]