当前位置:网站首页>You can have zongzi if you want, but you have to go through my authentication and authorization

You can have zongzi if you want, but you have to go through my authentication and authorization

2022-06-10 06:50:00 Running Wang Mumu sir

s p r i n g b o o t in Such as What Add Enter into Ann whole \textcolor{Orange}{springboot How to add security in } springboot in Such as What Add Enter into Ann whole
learn xi too cheng in Of pen remember , Fang then check reading learn xi \textcolor{green}{ Notes in the learning process , It's easy to check and learn } learn xi too cheng in Of pen remember , Fang then check reading learn xi
pen remember total junction Come on Source On Depending on the frequency B standing crazy god say \textcolor{green}{ The summary of notes comes from the video B Stand up and say } pen remember total junction Come on Source On Depending on the frequency B standing crazy god say
Welcome to pay attention and praise ️ Collect messages

Security is a non functional requirement .

Official website :https://spring.io/projects/spring-security

Make a website : Safety should be considered at the beginning of the design .

shiro,SpringSecurity: Except that the class and name are different , Everything else is the same . The main function is authentication and authorization .

be used for : Function permissions , Access right , Menu permissions

Actual operation

  1. Create a project and put web Module and Thymeleaf Module introduction

     Insert picture description here

  2. Import the static file into

     Insert picture description here

  3. Turn off the template engine cache , Convenient debugging

    spring.thymeleaf.cache=false
    
  4. To configure controller

    package com.hxl.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;
        }
    }
    
  5. Start the test localhost:8080 Run successfully

Spring Security

Spring Security Is aimed at Spring Project security framework , It's also Spring Boot The default technology selection of the underlying security module , He can achieve powerful Web safety control , For security control , We just need to introduce spring-boot-starter-security modular , Make a small amount of configuration , To achieve strong security management !

Remember a few classes :

  • WebSecurityConfigurerAdapter: Customize Security Strategy
  • AuthenticationManagerBuilder: Custom authentication policy
  • @EnableWebSecurity: Turn on WebSecurity Pattern

Spring Security The two main goals of are “ authentication ” and “ to grant authorization ”( Access control ).

“ authentication ”(Authentication)

Authentication is about verifying your credentials , Such as user name / user ID And password , To verify your identity .

Authentication is usually done with a user name and password , Sometimes used in combination with authentication factors .

“ to grant authorization ” (Authorization)

Authorization occurs after the system has successfully verified your identity , Finally, you will be granted access to resources ( Such information , file , database , Money , Location , Almost anything ) Full authority of .

The concept is universal , Not just in Spring Security in .

Certificate authority

  1. introduce Spring Security modular

    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    
  2. To write config

    Official website :https://spring.io/projects/spring-security

  3. Write basic configuration class

    package com.hxl.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;
    
    @EnableWebSecurity // Turn on WebSecurity Pattern 
    public class Security extends WebSecurityConfigurerAdapter {
          
        // Chain programming 
        @Override
        protected void configure(HttpSecurity http) throws Exception {
          
            super.configure(http);
        }
    }
    
  4. Custom authorization

    @Override
    protected void configure(HttpSecurity http) throws Exception {
          
        // The home page is accessible to everyone , The function page can only be accessed by the corresponding authorized person 
        /*http.authorizeRequests() This is an authentication request , hinder . It means that you can access */
        http.authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/level1/**").hasRole("vip1")
            .antMatchers("/level2/**").hasRole("vip2")
            .antMatchers("/level3/**").hasRole("vip3");
    }
    
  5. test

    At this time, we found that , In addition to the home page , Nothing else can get in , This is because you do not have permission to log in to the role

  6. Turn on login configuration

    In the custom authorization method above , Add the following code

    // No permission to jump to the login page by default , You need to open the login page 
    http.formLogin();
    
  7. test

    If you don't have permission , Will automatically jump to the login page , And the jump link is http://localhost:8080/login

  8. authentication

    // authentication , You can authenticate in memory , You can also authenticate in the database 
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          
        auth.inMemoryAuthentication()
            .withUser("hxl").password("{noop}123456").roles("vip1","vip2")
            .and()
            .withUser("root").password("{noop}123456").roles("vip1","vip2","vip3")
            .and()
            .withUser("wode").password("{noop}123456").roles("vip1");
    }
    
  9. Pay attention to the top

    I found that a new password has been added to the password column {noop} This is because if you do not add this, the following problem will be reported
     Insert picture description here

    This is due to encryption , The password transmitted from the front end should be encrypted in some way , Of course, in addition to the above methods, the following methods can be used for encryption .

    auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
              .withUser("hxl").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2");
    

    This way is also possible . The official recommendation is Use bcrypt encryption

  10. test

    After that, it is found that each user can only access the rules under his own authentication . No access to other , Otherwise, an error will be reported

     Insert picture description here

Access control and logout

  1. First, enable the configured logoff function

    Add the following logoutSuccessUrl After the logout is successful , You can still jump to the home page

    // Chain programming 
        @Override
        protected void configure(HttpSecurity http) throws Exception {
          
            //....
            // Cancellation , Turn on the logout function , Jump to home page 
            http.logout().logoutSuccessUrl("/");
        }
    
  2. Add a logout button

    <!-- Cancellation -->
    <a class="item" th:href="@{/logout}">
        <i class="sign-out icon"></i>  Cancellation 
    </a>
    
  3. test

     Insert picture description here

     Insert picture description here

    Click to log out , And you can return to the home page .

  4. Function optimization

    After successful login , The navigation bar displays the user information and the logout button . If there is no login, only the login button will be displayed . At the same time, the home page displays only the pages that the user has permission .

  5. Login, logout and user information

    • Download dependency

      <!-- 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>
      
    • stay index.html in

      Add namespace

      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
      

      If you are writing the following sec There was no hint when I was , Modify the namespace to

      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
      

      Modify login / logout function and navigation bar

      <!-- Log in and log out -->
      <div class="right menu">
          <!-- Not logged in -->
          <div sec:authorize="!isAuthenticated()">
              <a class="item" th:href="@{/toLogin}">
                  <i class="address card icon"></i>  Sign in 
              </a>
          </div>
          <!-- Logged in -->
          <div sec:authorize="isAuthenticated()">
              <a class="item">
                  <i class="address card icon"></i>
                   user name :<span sec:authentication="principal.username"></span>
                   role :<span sec:authentication="principal.authorities"></span>
              </a>
          </div>
          <!-- Cancellation -->
          <div sec:authorize="isAuthenticated()">
              <a class="item" th:href="@{/logout}">
                  <i class="address card icon"></i>  Cancellation 
              </a>
          </div>
      </div>
      
  6. Role function certification

    Take, for example , Others can be added .

     Insert picture description here

    <div class="column" sec:authorize="hasRole('vip1')">
    
  7. test

     Insert picture description here

  8. Note that we have to go to when logging in http://localhost:8080/login This page , Not what we started with http://localhost:8080/toLogin. Next, we need to solve this problem .

Remember me

@Override
protected void configure(HttpSecurity http) throws Exception {
    
    // The home page is accessible to everyone , The function page can only be accessed by the corresponding authorized person 
    /*http.authorizeRequests() This is an authentication request , hinder . It means that you can access */
    http.authorizeRequests()
        .antMatchers("/").permitAll()
        .antMatchers("/level1/**").hasRole("vip1")
        .antMatchers("/level2/**").hasRole("vip2")
        .antMatchers("/level3/**").hasRole("vip3");
    // No permission to jump to the login page by default , You need to open the login page 
    http.formLogin();

    // Cancellation , Turn on the logout function , Jump to home page 
    http.logout().logoutSuccessUrl("/");

    // Turn on remember me 
    http.rememberMe();
}

 Insert picture description here

This is the default login , If you need to log in on your own login page, you still need to do something

How to complete it ?

After we close the browser , Log in again , You can find that users still exist . So how to achieve it ? Let's take a look at the browser cookie, I found him , And the default save time is two weeks .

 Insert picture description here

After successful login , take cookie Send to browser to save , Log in later and bring this cookie, As long as you pass the check, you can log in free . Once deleted manually cookie after , Then it won't exist .

A complete home page

Just add this code later . But it should be consistent with the front end .

// No permission to jump to the login page by default , You need to open the login page 
// Customize the landing page 
http.formLogin().loginPage("/toLogin");

 Insert picture description here

If the front end is login Then the back end needs to become

// Customize the landing page 
http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");

At the same time, if the form information is inconsistent with the default information, it needs to be modified

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

It's over .

  • Add the function of remembering me

    <div class="field">
        <input type="checkbox" name="remember">  Remember me 
    </div>
    
  • The backend needs to be validated

    // Turn on the function of remembering me , Customization remember that I receive the parameters of the front end 
    http.rememberMe().rememberMeParameter("remember");
    

test

 Insert picture description here

原网站

版权声明
本文为[Running Wang Mumu sir]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206100641319906.html