I heard that if you search the public account “Java Fish boy” on wechat, you will improve your skills to the next level

(1) Overview

The most important thing for a Web project is not how cool the features are, but how secure the project is. As everyone who has done projects knows, a project must pass security leak sweep before going online, and only after passing security leak sweep can the project be officially launched. Spring Security is a powerful and highly customizable authentication and access control framework, along with Shiro. Spring Security does two main things, authentication and authorization.

(II) Preliminary project construction

To better demonstrate SpringSecurity, let’s build a simple Web project. Introduce the Thymeleaf dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
Copy the code

Create a new landing page, a home page, and several display pages of different levels: login.html

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Landing page</title>
</head>
<body>
<div>
    <form>
        <h2>Landing page</h2>
        <input type="text" id="username" placeholder="username">
        <input type="password" id="password" placeholder="password">
        <button type="button">landing</button>
    </form>
</div>
</body>
</html>
Copy the code

The home page, index.html, mainly shows different levels of buttons, for later authorization preparation

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home page</title>
</head>
<body>
<div>
    <h2>Home page</h2>
    <a href="/login">landing</a>
    <div style="overflow: hidden">
        <div style="float: left; margin-left: 20px">
            <h3>level1</h3>
            <a href="/level1/1">level-1-1</a>
            <hr>
            <a href="/level1/2">level-1-2</a>
        </div>
        <div style="float: left; margin-left: 20px">
            <h3>level2</h3>
            <a href="/level2/1">level-2-1</a>
            <hr>
            <a href="/level2/2">level-2-2</a>
        </div>
        <div style="float: left; margin-left: 20px">
            <h3>level3</h3>
            <a href="/level3/1">level-3-1</a>
            <hr>
            <a href="/level3/2">level-3-2</a>
        </div>
    </div>
</div>
</body>
</html>
Copy the code

There are also several pages with different levels

Write your corresponding number in the body.

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
level-1-1
</body>
</html>
Copy the code

Finally, write a controller to receive the request:

@Controller
public class RouteController {
    @RequestMapping({"/","/index"})
    public String index(a){
        return "index";
    }
    @RequestMapping("/login")
    public String toLogin(a){
        return "login";
    }
    @RequestMapping("/level1/{id}")
    public String level1(@PathVariable("id")String id){
        return "level1/"+id;
    }
    @RequestMapping("/level2/{id}")
    public String level2(@PathVariable("id")String id){
        return "level2/"+id;
    }
    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable("id")String id){
        return "level3/"+id; }}Copy the code

The final effect is as follows:The homepage effect is as follows:

(3) Authentication and authorization

There are two problems in the above page. The first is that login authentication has not been processed. The second and third level pages can be accessed by all people now, without authorization. Both of these problems can be solved with SpringSecurity.

To implement SpringSecurity, you only need to introduce the spring-boot-starter-Security dependency and perform a few configurations to achieve powerful security management functions.

There are a few classes we need to keep in mind before we begin our formal contact:

1. WebSecurityConfigurerAdapter: custom Security strategy

2. AuthenticationManagerBuilder: custom authentication strategy

3.@EnableWebSecurity: Enable the WebSecurity mode

We create a new config package, create a configuration class SecurityConfig, WebSecurityConfigurerAdapter interface inheritance

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    / / authorization
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Only authorized users can access the level page
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
        // No permissions default to jump to the login page, redirected to /login by default
        http.formLogin();
    }
    / / certification
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1"."vip2"."vip3")
                .and()
                .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1"); }}Copy the code

Through the above code, to achieve authorization and authentication functions, authentication methods in memory stored user information. In normal cases, user data is obtained from the database, and the authorization function sets different roles for different pages.

Again, we open the http://localhost:8080/ home page, all people have access to, when we click on the link in the level1 within 2 3, automatically jump to the http://localhost:8080/login

You will find that the landing page is clearly not their own, how to appear? That’s exactly what SpringSecurity provides, http.formlogin (); This code does the login page processing, no permission default jump to the login page, the default redirection to /login.

When we log in with an account with different permissions, we can click the link with different permissions. If we click the link with different permissions, we will report error 403

(4) Deregistration operations

Since you have authentication and authorization, you must be able to log out. SpringSecurity is easy to log out. You just need to add a code to the authorization code of the SecurityConfig class.

/ / logout
http.logout();
Copy the code

Then add a logoff tag to the front-end index.html code

<a href="/logout">The cancellation</a>
Copy the code

Click the logout button on the home page to jump to SpringSecurity’s logout prompt screenClick the logout button to automatically exit to the login page. If you want to return to the homepage after logout, you can modify the logout code as follows:

http.logout().logoutSuccessUrl("/");
Copy the code

(5) Remember password function

In general, there will be a login page to remember the password function, this function is actually in the local generation of a cookie, although it is not difficult to use the native Java implementation, but also need some code. With SpringSecurity, you only need one line:

http.rememberMe();
Copy the code

When you re-enter the login page, you can see the option to remember your password has been added