SpringBoot整合SpringSecurity安全框架

  1. 需要的依赖

    1. <dependencies>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-thymeleaf</artifactId>
              </dependency>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-web</artifactId>
              </dependency>
      
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-devtools</artifactId>
                  <scope>runtime</scope>
                  <optional>true</optional>
              </dependency>
              <dependency>
                  <groupId>org.projectlombok</groupId>
                  <artifactId>lombok</artifactId>
                  <optional>true</optional>
              </dependency>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-security</artifactId>
              </dependency>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-test</artifactId>
                  <scope>test</scope>
              </dependency>
      
              <!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4 -->
              <dependency>
                  <groupId>org.thymeleaf.extras</groupId>
                  <artifactId>thymeleaf-extras-springsecurity5</artifactId>
                  <version>3.0.4.RELEASE</version>
              </dependency>
          </dependencies>
      
  2. 页面结构
    image

  3. 创建config包,在config包下面创建SecurityConfig类

    1. package com.xh.springsecurity01.config;
      
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.context.annotation.Configuration;
      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.WebSecurityConfigurerAdapter;
      import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
      
      import javax.naming.Context;
      import javax.sql.DataSource;
      
      /**
       * @author Admins
       */
      @Configuration
      public class SecurityConfig extends WebSecurityConfigurerAdapter {
          @Override
          public void configure(HttpSecurity security) throws Exception {
              System.out.println("security ....");
              security.authorizeRequests()
                      //所有人可以访问
                      .antMatchers("/").permitAll()
                      //哪些角色可以访问 这个请求
                      .antMatchers("/level/1").hasRole("vip1")
                      .antMatchers("/level/2").hasRole("vip2")
                      .antMatchers("/level/3").hasRole("vip3");
      
              //没有权限进入到login
              //跳转到指定的登录页面
              security.formLogin().loginPage("/login");
              //注销
              //默认是返回到登录了页面, logoutSuccessUrl 注销成功后返回到指定页面
              security.logout().logoutSuccessUrl("/");
      
              //关闭csrf跨站攻击,否则注销会404
              security.csrf().disable();
      
              //开启记住我  前端记住我复选框的name是remeberMe,那么rememberMeParameter的值就是什么remeberMe
              security.rememberMe().rememberMeParameter("rememberMe");
          }
      
          @Override
          protected void configure(AuthenticationManagerBuilder auth) throws Exception {
              //演示,将username and password 存到内存中,没有连接到数据库
              //passwordEncoder 密码加密方式
              //withUser 用户名,password 密码,roles 角色授权
              auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                      .withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1", "vip2", "vip3")
                      .and()
                      .withUser("mucd").password(new BCryptPasswordEncoder().encode("mucd")).roles("vip1", "vip2");
          }
      }
      
      
  4. controller

  5. 这里的controller主要是跳转用的

  6. package com.xh.springsecurity01.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 toIndex() {
            return "index";
        }
    
        @RequestMapping("login")
        public String toLogin() {
            return "login";
        }
    
        @RequestMapping("/level/{id}")
        public String toLevel(@PathVariable("id") int id) {
            return "level/" + id;
        }
    }
    
  7. 主页html

    1. <!DOCTYPE html>
      <!-- thymeleaf整合springboot-security的命名空间 -->
      <html lang="en" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
      <head>
          <meta charset="UTF-8">
          <title>INDEX</title>
      </head>
      <body>
      <div>
          <div sec:authorize="isAuthenticated()">
              <a href="/logout">注销</a>
          </div>
          <!--如果没有登录则显示,已经登录隐藏-->
          <div sec:authorize="!isAuthenticated()">
              <a href="/login">登录</a>
              <h1>还没登录,登陆后显示信息</h1>
          </div>
      
          <hr>
      </div>
      <!--如果已经登录显示用户名-->
      <div sec:authorize="isAuthenticated()">
          用户名:<span sec:authentication="principal.username"></span>
          角色:<span sec:authentication="principal.authorities"></span>
      </div>
      <hr>
      <!--
      用户角色权限等级
      如果是指定等级,则显示该元素,否则不显示
      -->
      <p sec:authorize="hasRole('vip1')">
          <a href="/level/1">level 01</a>
      </p>
      <p sec:authorize="hasRole('vip2')">
          <a href="/level/2">level 02</a>
      
      </p>
      <p sec:authorize="hasRole('vip3')">
          <a href="/level/3">level 03</a>
      </p>
      
      </body>
      </html>
      
      
      
      
      
  8. 登录页

    1. <!DOCTYPE html>
      <html lang="en"
            xmlns="http://www.thymeleaf.org/"
      >
      <head>
          <meta charset="UTF-8">
          <title>Title</title>
      </head>
      <body>
      <form action="/login" method="post">
          <input name="username" type="text" placeholder="username"><br>
          <input name="password" type="password" placeholder="pwd"><br>
          <!--这里的name属性 要和SecurityConfig的security.rememberMe().rememberMeParameter("rememberMe")值相同 -->
          记住我 <input type="checkbox" name="rememberMe"><br>
          <input type="submit" value="submit"><br>
      </form>
      </body>
      </html>
      
posted on 2021-12-14 16:09  MucdIng  阅读(32)  评论(0)    收藏  举报