SpringBoot integration SpringSecurity Origins (Zero)

This is the first article on SpringSecurity. It mainly introduces what SpringSecurity is and how to use it in SpringBoot

I. Basic knowledge

IO /spring-secu…

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

Use national language, simple and abstract say its definition

  • Very 🐂 authentication and access verification framework

So what exactly can we do?

  • User login authentication: User name + password login to determine the user identity
  • User access authentication (common ACL access control list, RBAC role access control) : Determines whether you have permission to access a resource
  • Security protection (CSRF cross-site attack,Session Fixation attack…)

II. The early experience

Let’s look at how to use springsecurity in springboot

1. The configuration

The relatively complete POM configuration is as follows (note that we are using springBoot version 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>
Copy the code

2. Examples of the demo

After the above configuration, nothing needs to be done, the project is already connected to Spring Security; Services in the project require login to access them

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

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

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

When we need to access the home page, we will find a direct 302 redirection to the login page, as shown below

Using the generated security password: AA410186-5C04-4282-b217-507ffb1f61eb

After login, it will be redirected back to the URL we visited before. As can be seen from packet capture, after successful login, the cookie of the requester will be set. Subsequent requests carry cookies to indicate the user’s identity

3. Basic configuration

This is an example of a first hello World project, but the default username/password is a bit spooky, The default configuration mainly comes from the org. Springframework. Boot. Autoconfigure. Security. SecurityProperties. User, below is a screenshot (so in front of the User named User)

Next we need to configure it in a human-friendly way by specifying the login username/password in the project’s configuration file application.yml

spring:
  security:
    user:
      name: yihuihui
      password: 123456
Copy the code

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

4. Obtaining user identity

Although the above is a simple case, there is another point that has to be mentioned. In my interface, although I know you are logged in, how can I know who you are?

We can get the login user directly via HttpServletRequest#getRemoteUser(); Or by SecurityContextHolder. GetContext (). GetAuthentication () getPrincipal () to obtain authorization information

So let’s write a general method

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

// or
public Object getUser(a) {
    SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
Copy the code

And then change our service interface a little bit

@GetMapping(path = {"/"."/index"})
public String index(a) {
    return "hello this is index! welcome " + getUser();
}
Copy the code

After a second visit, the results are as follows

5. Summary

This article is the origin of the SpringSecurity series. The first section introduces what SpringSecurity is and what its features are

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

The second section introduces a simple example of HelloWorld

  • Springboot project to add dependenciesspring-boot-starter-security; All HTTP interface access requires a login. By default, the user name is user and the password is the UUID string output by the console
  • throughspring.security.user.nameandspring.security.user.passwordTo specify the username and password
  • throughHttpServletRequest#getRemoteUser()Obtaining a Login User

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

II. The other

0. Project

  • Project: github.com/liuyueyi/sp…
  • Code: github.com/liuyueyi/sp…

1. An ashy Blog

As far as the letter is not as good, the above content is purely one’s opinion, due to the limited personal ability, it is inevitable that there are omissions and mistakes, if you find bugs or have better suggestions, welcome criticism and correction, don’t hesitate to appreciate

Below a gray personal blog, record all the study and work of the blog, welcome everyone to go to stroll

  • A grey Blog Personal Blog blog.hhui.top
  • A Grey Blog-Spring feature Blog Spring.hhui.top