Spring Security

Mainstream Security frameworks: Shiro, Spring Security: similar, except for different classes and names

Function:

  • Access-control: indicates access control
  • Customizable Authentication: Customizable authentication

1. Create projects

If you create a quick start project from the official SpringBoot website, you may encounter a visit to the situation of no response, it is recommended to use aliyun address

https://start.aliyun.com/

2. Import resources

Web Template Resources

The template cache is turned off

spring.thymeleaf.cache=false
Copy the code

Create a controller to redirect the view

package com.gip.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class RouterController {
    @GetMapping({"/", "/index"})
    public String index(a) {
        return "index";
    }

    @RequestMapping("/toLogin")
    public String toLogin(a) {
        return "views/login";
    }

    @RequestMapping("/level1/{id}")
    public String level1(@PathVariable("id") int id) {
        return "views/level1/"+id;
    }

    @RequestMapping("/level2/{id}")
    public String level2(@PathVariable("id") int id) {
        return "views/level2/" + id;
    }

    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable("id") int id) {
        return "views/level3/"+ id; }}Copy the code

useResultfulStyle pass parameter

Import Spring Security dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
Copy the code

Spring Security is a Security management framework in the Spring family. In fact, Spring Security has been developed for many years before the emergence of Spring Boot, but it is not used much. The field of Security management has always been dominated by Shiro.

Compared to Shiro, integrating Spring Security into SSM/SSH is a more cumbersome operation, so while Spring Security is more powerful than Shiro, But not as much as Shiro (Shiro doesn’t have as many features as Spring Security, but Shiro is adequate for most projects).

Since Spring Boot came along, Spring Boot provides an automated configuration solution for Spring Security that can be used with zero configuration.

Thus, in general, the common combination of security management stacks looks like this:

  • SSM + Shiro
  • Spring Boot/Spring Cloud + Spring Security

Note that this is just a recommended combination, and technically it will work no matter how it is combined.

Let’s see how it works.

Security generally consists of three parts: defining rules, authenticating users, and authorizing users

3. Set rules

New SecurityConfig class

package com.gip.config;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

//AOP: interceptor
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // Use chained programming
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3"); }}Copy the code

EnableWebSecurity: Declare the security configuration and let Spring host it

This class will inherit WebSecurityConfigurerAdapter

4. Authorization and authentication

 @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // Set the user in memory
        // The user should theoretically be read from the database
        auth.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("yang")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .roles("vip1")
                .and()
                .withUser("gip")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .roles("vip2"."vip3");
    }
Copy the code

Spring Security 5.0 adds multiple encryption methods and changes the default password format.

InMemoryAuthentication ().passwordencoder (new BCryptPasswordEncoder()), which is equivalent to using BCrypt encryption mode to process user passwords during login

The previous “.password(“123456″)” becomes.password(new BCryptPasswordEncoder().encode(“123”)), which is equivalent to Bcrypt encoding the password in memory. If the password is the same, the login is allowed only when the password is correct.

Rerun the project for testing

After you log in to the account, you have permission to access it

5. Logout and permission control

Add the following code to the configure method

  // No permission, default to the login page
        http.formLogin();
        // Enable the logout function
        // Logout successful, jump to home page
        http.logout()
                .logoutSuccessUrl("/");
Copy the code

Add an entry for logout on the Index page

<a th:href="@{/logout}">
    <i class="sign-out icon"></i>The cancellation</a>
Copy the code

To run the project, log in first and then click the Logout button

After confirmation, the logout success page is returned, which is set as/home page

Add dependencies thymeleaf-SpringSecurity5 consolidation package

<! -- Thymeleaf-SpringSecurity5 integration package --> <! -- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity5 --> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity5</artifactId> < version > 3.0.4. RELEASE < / version > < / dependency >Copy the code

Import namespaces in HTML: There you go!

xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
Copy the code
           <! -- Login and logout -->
            <div class="right menu">
                <! -- Not logged in -->
                <div sec:authorize=! "" isAuthenticated()">
                    <a class="item" th:href="@{/toLogin}">
                        <i class="address card icon"></i>The login</a>
                </div>

               <! -- Log in -->
                <div sec:authorize="isAuthenticated()">
                    <a class="item">The user name<span sec:authentication="principal.username"></span>
                     <! Orities :< SPAN SEC :authentication=" principal.getauthorities ()"></span>-->Role:<span sec:authentication="principal.authorities"></span>
                    </a>
                    <a th:href="@{/logout}">
                        <i class="sign-out icon"></i>The cancellation</a>
                </div>
                
            </div>
Copy the code

The tag attribute provided in the integration package can be used to determine whether the current user is logged in or not, so users who are not logged in will be displayed

Displays user information, including the user name and role

Note: This will return an error!!

GetAuthorities () can’t do it with GET; it goes directly to principal.authorities so that the attribute values do

Add the following properties to the Level1 module

<div class="content" sec:authorize="hasRole('vip1')">
Copy the code

Can be realized, according to the role to display the corresponding content, play the content of authority control

<div class="content" sec:authorize="hasRole('vip2')">
Copy the code
<div class="content" sec:authorize="hasRole('vip3')">
Copy the code

Test the

No login status directly access the home page

Log in to an account

The discovery shows part of the content

Test complete!

6. Remember me and home page customization

 // No permission, default to the login page
http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login").usernameParameter("user").passwordParameter("pwd");
Copy the code

LoginProcessingUrl (“/login”) The login form is submitted to this path /login

Remember me function:

// Enable the Remember me function
http.rememberMe().rememberMeParameter("remember");
Copy the code

Login screen

<! DOCTYPEhtml>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>The login</title>
    <! --semantic-ui-->
    <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
</head>
<body>

<! -- Master container -->
<div class="ui container">

    <div class="ui segment">

        <div style="text-align: center">
            <h1 class="header">The login</h1>
        </div>

        <div class="ui placeholder segment">
            <div class="ui column very relaxed stackable grid">
                <div class="column">
                    <div class="ui form">
                        <form th:action="@{/login}" method="post">
                            <div class="field">
                                <label>Username</label>
                                <div class="ui left icon input">
                                    <input type="text" placeholder="Username" name="user">
                                    <i class="user icon"></i>
                                </div>
                            </div>
                            <div class="field">
                                <label>Password</label>
                                <div class="ui left icon input">
                                    <input type="password" name="pwd">
                                    <i class="lock icon"></i>
                                </div>
                            </div>
                            <div class="field">
                                <input type="checkbox" name="remember">Remember that I</div>
                            <input type="submit" class="ui blue submit button"/>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div style="text-align: center">
            <div class="ui label">
                </i>registered</div>
            <br><br>
            <small>blog.kuangstudy.com</small>
        </div>
        <div class="ui segment" style="text-align: center">
            <h3>Spring Security Study by Qin Jiang</h3>
        </div>
    </div>


</div>

<script th:src="@ {/ qinjiang/js/jquery - 3.1.1. Min. Js}"></script>
<script th:src="@{/qinjiang/js/semantic.min.js}"></script>

</body>
</html>
Copy the code