SpringBoot quick start

Reference link

SpringBoot01: Hello,World!

SpringBoot02: preliminary study on operation principle

SpringBoot03: yaml configuration injection

SpringBoot04: JSR303 data verification and multi environment switching

SpringBoot05: principle of automatic configuration

SpringBoot06: Custom starter

SpringBoot07: integrating JDBC

SpringBoot08: integrating Druid

SpringBoot09: integrating MyBatis

SpringBoot10: static resource processing for Web development

SpringBoot11: Thymeleaf template engine

SpringBoot12: MVC auto configuration principle

Spring boot13: page internationalization

SpringBoot14: integrated Swagger ultimate

SpringBoot15: asynchronous, timed, mail tasks

SpringBoot16: rich text editor

Spring boot17: Dubbo and Zookeeper integration

SpringBoot18: integrating spring security

Integrate JDBC

Connect database in idea

When creating a project, the SQL module needs to be checked

Note: connection to @ localhost failed [08001] Could not create connection to database server. Attempt

Add after database path

?serverTimezone=GMT

that will do

application. Configuration of files in YML:

spring:
  datasource:
    username: root
    password: 123456
    #If the time zone is wrong, add a time zone configuration, which is ok. serverTimezone=UTC
    url: jdbc:mysql://localhost:3306?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

JDBCController:

package com.atxins.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class JDBCController {

    @Autowired
    JdbcTemplate jdbcTemplate;

    //Query all information in the database
    //Without entity classes and databases, how can I get them, Map
    @GetMapping("/userList")
    public List<Map<String,Object>> userList(){
        String sql ="select * from testspringjdbc.student";
        List<Map<String, Object>> list_maps = jdbcTemplate.queryForList(sql);
        return list_maps;
    }

    @GetMapping("/addUser")
    public String addUser(){
        String sql ="insert into testspringjdbc.student(id,name,age,gender) values (2,'xxx',22,'male')";
        jdbcTemplate.update(sql);
        return "add-ok";
    }

    @GetMapping("/updateUser/{id}")
    public String updateUser(@PathVariable("id") int id){
        String sql ="update testspringjdbc.student set name=?,age=?,gender=? where id="+id;
        //encapsulation
        Object[] objects = new Object[3];
        objects[0] = "Net gain";
        objects[1] = 22;
        objects[2] ="male";
        jdbcTemplate.update(sql,objects);
        return "update-ok";
    }

    @GetMapping("/deteleUser/{id}")
    public String deteleUser(@PathVariable("id") int id){
        String sql ="delete from testspringjdbc.student where id=?";
        jdbcTemplate.update(sql,id);
        return "delete-ok";
    }
}

In the test class, you can view some information of the data source:

package com.atxins;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@SpringBootTest
class Springboot04DataApplicationTests {
    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        //Check out the default data source: com zaxxer. hikari. HikariDataSource
        System.out.println(dataSource.getClass());

        //Get database connection
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        //XXX Template:Springboot has configured the template bean and CURD is ready to use

        //close
        connection.close();
    }

}

Integrate Druid

Introduction to Druid

A large part of Java programs need to operate the database. In order to improve the performance, they have to use the database connection pool when operating the database.

Druid is a database connection pool implementation on Alibaba's open source platform. It combines the advantages of C3P0, DBCP and other DB pools, and adds log monitoring.

Druid can well monitor the connection of DB pool and the execution of SQL. It is naturally a DB connection pool for monitoring.

Druid has deployed more than 600 applications in Alibaba, which has been severely tested by large-scale deployment in the production environment for more than a year.

Hikari data source is used by default above Spring Boot 2.0. It can be said that Hikari and Driud are the best data sources on the current Java Web. Let's focus on how Spring Boot integrates Druid data source and how to realize database monitoring.

Github address: https://github.com/alibaba/druid/

com. alibaba. druid. pool. The basic configuration parameters of druiddatasource are as follows:


Configure data source

1. Add Druid data source dependency on.

<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.23</version>
</dependency>

2. Switching data sources; As mentioned before, com.com is used by default for Spring Boot 2.0 and above zaxxer. hikari. Hikaridatasource data source, but it can be accessed through spring datasource. Type specifies the data source.

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource # Custom data source

3. After data source switching, inject DataSource into the test class, then obtain it, and output to see whether the switching is successful;

4. Switching succeeded! Now that the switch is successful, you can set the initialization size, maximum number of connections, waiting time, minimum number of connections and other settings of the data source connection; You can view the source code

spring:
  datasource:
    username: root
    password: 123456
    #If the time zone is wrong, add a time zone configuration, which is ok. serverTimezone=UTC
    url: jdbc:mysql://localhost:3306?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

      #Spring Boot does not inject these attribute values by default and needs to bind by itself
      #druid data source proprietary configuration
      initialSize: 5
      minIdle: 5
      maxActive: 20
      maxWait: 60000
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true

      #Configure filters for monitoring statistics interception, stat: monitoring statistics, log4j: logging, wall: defensive sql injection
      #If allowed, an error will be reported in Java lang.ClassNotFoundException: org. apache. log4j. Priority
      #Then import log4j dependency. Maven address: https://mvnrepository.com/artifact/log4j/log4j
      filters: stat,wall,log4j
      maxPoolPreparedStatementPerConnectionSize: 20
      useGlobalDataSourceStat: true
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

5. Dependency of import Log4j

<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

6. Now programmers need to bind the parameters in the global configuration file for DruidDataSource and add them to the container instead of using the automatic generation of Spring Boot; We need to add the DruidDataSource component to the container and bind the attribute;

package com.kuang.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class DruidConfig {

    /*
       Add the customized Druid data source to the container and no longer let Spring Boot create it automatically
       Bind the Druid data source attribute in the global configuration file to com alibaba. druid. pool. Druiddatasource to make them effective
       @ConfigurationProperties(prefix = "spring.datasource"): The function is to add the global configuration file
       The prefix is spring Inject the attribute value of datasource into com alibaba. druid. pool. Druiddatasource is in a parameter with the same name
     */
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

}

7. Test in the test class; See if it succeeds!

@SpringBootTest
class SpringbootDataJdbcApplicationTests {

   //DI injection data source
   @Autowired
   DataSource dataSource;

   @Test
   public void contextLoads() throws SQLException {
       //Take a look at the default data source
       System.out.println(dataSource.getClass());
       //Get connection
       Connection connection =   dataSource.getConnection();
       System.out.println(connection);

       DruidDataSource druidDataSource = (DruidDataSource) dataSource;
       System.out.println("druidDataSource Maximum connections to data source:" + druidDataSource.getMaxActive());
       System.out.println("druidDataSource Number of data source initialization connections:" + druidDataSource.getInitialSize());

       //Close connection
       connection.close();
   }
}

Output result: it can be seen that the configuration parameters have taken effect!

Configure Druid data source monitoring

Druid data source has the function of monitoring and provides a web interface for users to view. Similarly, when installing a router, people also provide a default web page.

Therefore, the first step is to set Druid's background management page, such as login account, password, etc; Configure background management;

//Configure the Servlet of Druid monitoring and management background;
//There is no web when the Servlet container is built in XML file, so the Servlet registration method of Spring Boot is used
@Bean
public ServletRegistrationBean statViewServlet() {
    ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");

    // These parameters can be found on COM alibaba. druid. support. http. StatViewServlet 
    // Parent class of com alibaba. druid. support. http. Found in resourceservlet
    Map<String, String> initParams = new HashMap<>();
    initParams.put("loginUsername", "admin"); //Login account of background management interface
    initParams.put("loginPassword", "123456"); //Login password of background management interface

    //Who is allowed to access in the background
    //initParams.put("allow", "localhost"): indicates that only the local machine can access it
    //initParams.put("allow", ""): when it is empty or null, it means that all access is allowed
    initParams.put("allow", "");
    //deny: Druid, who is denied access in the background
    //initParams.put("kuangshen", "192.168.1.20"); Indicates that this ip access is prohibited

    //Set initialization parameters
    bean.setInitParameters(initParams);
    return bean;
}

After configuration, we can choose to access:

After entering

Configure Druid web monitoring filter

//Configure the filter for web monitoring of Druid monitoring
//WebStatFilter: used to configure management association monitoring statistics between Web and Druid data sources
@Bean
public FilterRegistrationBean webStatFilter() {
    FilterRegistrationBean bean = new FilterRegistrationBean();
    bean.setFilter(new WebStatFilter());

    //exclusions: sets which requests are filtered and excluded so that statistics are not performed
    Map<String, String> initParams = new HashMap<>();
    initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*");
    bean.setInitParameters(initParams);

    //"/ *" means to filter all requests
    bean.setUrlPatterns(Arrays.asList("/*"));
    return bean;
}

At ordinary times, it can be configured according to the needs during work, which is mainly used for monitoring!

Integrate Mybatis

Integration test

1. Dependencies required to import MyBatis

Think<!--introduce mybatis,This is Mybatis Officially provided adaptations SpringBoot Yes, not SpringBoot own-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>

2. Configuration yml file (startup fails when using application.properties file)

application.yml

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/testspringjdbc?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
#Integrate mybatis
mybatis:
  type-aliases-package: com.atxins.pojo
  mapper-locations: classpath:mybatis/mapper/*.xml

3. Test whether the database connection is successful!

package com.atxins;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.SQLException;

@SpringBootTest
class Springboot05MybatisApplicationTests {
    @Autowired
    DataSource dataSource;
    @Test
    void contextLoads() throws SQLException {
        System.out.println(dataSource.getClass());
        System.out.println(dataSource.getConnection());
    }

}

4. Create an entity class and import Lombok!

 <dependency>
     <groupId>org.projectlombok</groupId>
     <artifactId>lombok</artifactId>
 </dependency>

Student.java

package com.atxins.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    private int id;
    private String name;
    private int age;
    private String gender;
}

5. Create Mapper directory and corresponding Mapper interface

StudentMapper.java

package com.atxins.mapper;

import com.atxins.pojo.Student;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

//This annotation indicates that this is a mapper class of mybatis: Dao
@Mapper
@Repository
public interface StudentMapper {
    List<Student> queryStudentList();

    Student queryStudentById(Integer id);

    int addStudent(Student student);

    int updateStudent(Student student);

    int deleteStudent(int id);
}

6. Corresponding Mapper mapping file (placed in the resources directory)

StudentMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atxins.mapper.StudentMapper">
    <select id="queryStudentList" resultType="Student">
        select * from student
    </select>

    <select id="queryStudentById" resultType="Student">
        select * from student where id =#{id}
    </select>

    <insert id="addStudent" parameterType="Student">
        insert into student (id,name,age,gender) values(#{id},#{name},#{age},#{gender})
    </insert>

    <update id="updateStudent" parameterType="Student">
        update student set name=#{name},age=#{age},gender=#{gender} where id=#{id}
    </update>

    <delete id="deleteStudent" parameterType="int">
        delete  from student where  id=#{id}
    </delete>
</mapper>

7. Write the student's StudentController for testing!

package com.atxins.controller;

import com.atxins.mapper.StudentMapper;
import com.atxins.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class StudentController {

   @Autowired
   private StudentMapper studentMapper;

   @GetMapping("/queryStudentList")
   public List<Student> queryStudentList(){
       List<Student> studentList = studentMapper.queryStudentList();
       for (Student student : studentList) {
           System.out.println(student);
       }
       return studentList;
   }

   @GetMapping("/queryStudentById/{id}")
   public Student queryStudentById(@PathVariable("id") Integer id){
       Student s1 = studentMapper.queryStudentById(id);

       return s1;
   }

   //Add a student
   @GetMapping("/addStudent")
   public String addStudent(){
       studentMapper.addStudent(new Student(5,"Ma",25,"male"));

       return "ok";
   }

   //Modify a student
   @GetMapping("/updateStudent")
   public String updateStudent(){
       studentMapper.updateStudent(new Student(5,"It's almost half",26,"female"));
       return "ok";
   }

   //Delete student by id
   @GetMapping("/deleteStudent")
   public String deleteStudent(){
       studentMapper.deleteStudent(5);
       return "ok";
   }

}

Start project access for testing! Enter the corresponding access path in the address bar: http://localhost:8080/ +…

Integrated spring security

Spring security

Spring Security is a powerful and highly customizable authentication and access control framework. It is actually the standard for protecting spring based applications.

Spring Security is a framework that focuses on providing authentication and authorization for Java applications. Like all spring projects, the real strength of Spring Security is that it can be easily extended to meet customization needs

Based on the Spring framework, Spring Security provides a complete solution for Web application security. Generally speaking, the security of Web application includes two parts: user Authentication and user Authorization. User Authentication refers to verifying whether a user is a legal subject in the system, that is, whether the user can access the system. User Authentication generally requires users to provide user name and password. The system completes the Authentication process by verifying the user name and password. User Authorization refers to verifying whether a user has permission to perform an operation. In a system, different users have different permissions. For example, for a file, some users can only read it, while others can modify it. Generally speaking, the system assigns different roles to different users, and each role corresponds to a series of permissions.

For the two application scenarios mentioned above, the Spring Security framework has good support. In terms of user authentication, the Spring Security framework supports mainstream authentication methods, including HTTP basic authentication, HTTP form authentication, http digest authentication, OpenID and LDAP. In terms of user authorization, Spring Security provides role-based access control and Access Control List (ACL), which can carry out fine-grained control over domain objects in applications.

Actual test

Construction of experimental environment

1. Create an initial springboot project web module, thymeleaf module

<!--thymeleaf Template-->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>

2. Import static resources

3. controller jump!

package com.atxins.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class RouterController {
    @RequestMapping({"/","/index"})
    public String index(){
        return "index";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        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;
    }
}

4. Test whether the experimental environment is OK! Address bar access http://localhost:8080/

Understanding spring security

Spring Security is the security framework for the spring project and the default technology selection of the underlying security module of Spring Boot. It can realize powerful Web security control. For security control, we only need to introduce the Spring Boot starter security module and make a small amount of configuration to realize powerful security management!

Remember several categories:

  • WebSecurityConfigurerAdapter: custom Security policy
  • AuthenticationManagerBuilder: custom authentication policy
  • @EnableWebSecurity: enable WebSecurity mode @ Enablexxx: enable a function

The two main goals of Spring Security are "authentication" and "authorization" (access control).

Authentication

Authentication is about verifying your credentials, such as user name / user ID and password, to verify your identity.

Authentication is usually done by user name and password, sometimes in combination with authentication factors.

Authorization

Authorization occurs after the system successfully verifies your identity, and will eventually grant you full access to resources (such as information, files, databases, funds, locations, almost anything).

This concept is universal, not just in Spring Security.

Certification and authorization

At present, everyone can access our test environment. We use Spring Security to add the functions of authentication and authorization

1. Introducing Spring Security module

<!--security-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2. Write Spring Security basic configuration class

Refer to the official website: https://spring.io/projects/spring-security

Check the version in our own project and find the corresponding help document in learn.

Fixed format:

SecurityConfig:

package com.atxins.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

//AOP: interceptor
@EnableWebSecurity // Enable WebSecurity mode
public class SecurityConfig  extends WebSecurityConfigurerAdapter {
    //Authorization chain programming
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // The home page can be accessed by everyone, and the function page can only be accessed by people with corresponding permissions
        //Rules for requesting authorization
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
        //If you don't have permission, you will go to the login page by default. You need to open the login page
        http.formLogin();
    }

    //Springboot 2.1. Authentication X can be used directly
    //Password code: PasswordEncoder, which adds many encryption methods in spring security 5.0 +
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //These data should be read from the database normally
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
               .withUser("Axin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
               .and()
               .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}

Double click Shift: find files in all directories of the project / global search method

Permission control and logoff

1. Turn on the auto configured logoff function

//Authorization rules for custom requests
@Override
protected void configure(HttpSecurity http) throws Exception {
   //....
   //Turn on the auto configured logoff function
      // /Logout logout request
   http.logout();
}

2. In the front end, we add a logout button, index HTML navigation bar

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

3. However, we want him to log off successfully and still jump to the home page. What should we do?

// .logoutSuccessUrl("/");  Log out successfully and come to the home page
http.logout().logoutSuccessUrl("/");

4. Now we have another requirement: when the user does not log in, the navigation bar only displays the login button. After the user logs in, the navigation bar can display the login user information and logout button! Also, for example, kuangshen has only vip2 and vip3 functions, so only these two functions are displayed when logging in, but the function menu of vip1 is not displayed! This is the real website! How to do it?

We need to combine some functions in thymeleaf

sec: authorize = "isAuthenticated()": whether to authenticate login! To display different pages

Maven dependency:

<!--security-thymeleaf Integration package-->
<dependency>
   <groupId>org.thymeleaf.extras</groupId>
   <artifactId>thymeleaf-extras-springsecurity5</artifactId>
   <version>3.0.4.RELEASE</version>
</dependency>

The security thyme EAF integration package is introduced. Its functions will not be supported. The springboot version is too high and needs to be downgraded.

<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.9.RELEASE</version>

5. Modify our front page

  1. Import namespace

  2. xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
    
  3. Modify the navigation bar and add authentication judgment

<!--Login and logout-->
<div class="right menu">
    <!--If you are not logged in-->
    <div sec:authorize="!isAuthenticated()">
        <a class="item" th:href="@{/toLogin}">
            <i class="address card icon"></i> Sign in
        </a>
    </div>
    <!--If login:User name, logout-->
    <div sec:authorize="isAuthenticated()">
        <a class="item" >
             user name:<span sec:authentication="principal.username"></span>
          	 Role:<span sec:authentication="principal.authorities"></span>
        </a>
    </div>
    <div sec:authorize="isAuthenticated()">
        <a class="item" th:href="@{/logout}">
            <i class="sign-out icon"></i>cancellation
        </a>
    </div>
</div>

6. Restart the test. We can log in and try. After successful login, the page we want is displayed;

7. If you log off 404, it is because it prevents CSRF Cross Site Request Forgery by default, because it will cause security problems. We can change the request to post form submission, or turn off the CSRF function in spring security; Let's try: add HTTP to the configuration csrf(). disable();

http.csrf().disable();//Turn off csrf function: Cross Site Request Forgery. By default, logout requests can only be submitted through post

8. We continue to complete the following role function block authentication!

<div class="ui three column stackable grid">
        <!--The menu is dynamically implemented according to the user's role-->
        <div class="column" sec:authorize="hasRole('vip1')">
            <div class="ui raised segment">
                <div class="ui">
                    <div class="content">
                        <h5 class="content">Level 1</h5>
                        <hr>
                        <div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div>
                        <div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
                        <div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="column" sec:authorize="hasRole('vip2')">
            ...
        </div>

        <div class="column" sec:authorize="hasRole('vip3')">
          ...
    	</div>
</div>

9. Test it! Permission control and logout are done!

Remember me

In the current situation, as long as we log in, close the browser and log in again, we will log in again. However, in the case of many websites, there is a function of remembering passwords. How can we achieve this? It's simple

1. Turn on the remember me function

//Authorization rules for custom requests
@Override
protected void configure(HttpSecurity http) throws Exception {
		. . . . . . 
    //Enable the remember me function essence cookie and save it for two weeks by default
   http.rememberMe();
}

2. We started the project again and found that the login page had an additional remember me function. After logging in, we closed the browser, and then reopened the browser to access. We found that the user still exists!

Thinking: how to achieve it? It's actually very simple

We can view the browser's cookie s

3. Delete the client and server of cookies at the same time, and the information of cookies will not be saved.

**Conclusion: * * after successful login, send the cookie to the browser for saving. After login, take this cookie with you. As long as you pass the check, you can avoid login. If you click log off, the cookie will be deleted.

Custom landing page

Now this Login page is the default of spring security. How can we use the Login interface written by ourselves?

1. Specify loginpage after the login page configuration just now

http.formLogin().loginPage("/toLogin");

2. Then the front end also needs to point to the login request defined by ourselves

<a class="item" th:href="@{/toLogin}">
   <i class="address card icon"></i> Sign in
</a>

3. When we log in, we need to configure where to send these information. Login HTML configure the submission request and method. The method must be post:

When this request is submitted, we still need to verify it. What should we do? We can check the source code of formLogin() method! We configure the parameters of receiving login user name and password!

http.formLogin()
  .usernameParameter("username")
  .passwordParameter("password")
  .loginPage("/toLogin")
  .loginProcessingUrl("/login"); // Login form submission request

5. Add the remember me multi selection box on the login page

<input type="checkbox" name="remember"> Remember me

6. Back end verification processing!

//Customize and remember my parameters!
http.rememberMe().rememberMeParameter("remember");

7. Test, OK

Distributed system theory

Reference link

Tags: Spring Boot

Posted by promovi on Thu, 12 May 2022 19:21:17 +0300