SpringBoot中SpringSecurity的使用

SpringSecurity

  • 简介:

    ​ Spring Security是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入spring-boot-starter-security模块,进行少量的配置,即可实简介现强大的安全管理!

    记住几个类:

    • WebSecurityConfigurerAdapter:自定义Security策略
    • AuthenticationManagerBuilder:自定义认证策略
    • @EnableWebSecurity:开启WebSecurity模式
    • Spring Security的两个主要目标是“认证”和“授权”(访问控制)。
      “认证”(Authentication)
      “授权”(Authorization)
      这个概念是通用的,而不是只在Spring Security中存在。
  • 引入依赖并关闭模板引擎

    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring5</artifactId>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-java8time</artifactId>
    </dependency
     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    
  • 导入资源

    在这里插入图片描述

  • controller层实现跳转

    package com.kuang.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","index.html"})
        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;
        }
    }
    





1. 用户认证和授权

配置控制类即可

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问,功能页只有对应有权限的人才能访问
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限默认会到登录页面,需要开启登录的页面
        http.formLogin();
    }

    //认证
    //密码编码
    //在SpringSecurity 5.0+ 新增了很多的加密方式
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //正常应该从数据库里读
            auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                    .and()
                    .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                    .and()
                    .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}





2. 注销及权限控制

  • 注销功能

    • 注销按钮

      <a class="item" th:href="@{/logout}">
          <i class="address card icon"></i> 注销
      </a>
      
    • 实现注销

      //注销 跳到首页
      http.logout().logoutSuccessUrl("/");
      
  • 实现未登录显示登录 登录之后显示用户名角色注销

    • 修改html页面

      <!--如果未登录-->
      <div sec:authorize="!isAuthenticated()">
          <a class="item" th:href="@{/toLogin}">
              <i class="sign-out icon"></i> 登录
          </a>
      </div>
      
      
      <!--如果已登录-->
      <div sec:authorize="isAuthenticated()">
          <a class="item">
              用户名:<span sec:authentication="name"></span>
              &nbsp;
              角色:<span sec:authentication="principal.authorities"></span>
          </a>
          <a class="item" th:href="@{/logout}">
              <i class="address card icon"></i> 注销
          </a>
      </div>
      
    • 导入整合包,降级springboot到2.0.9

      <parent>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-parent</artifactId>
          <version>2.0.9.RELEASE</version>
          <relativePath/> <!-- lookup parent from repository -->
      </parent>
      
      <!--security-thymeleaf整合包-->
      <dependency>
          <groupId>org.thymeleaf.extras</groupId>
          <artifactId>thymeleaf-extras-springsecurity4</artifactId>
          <version>3.0.4.RELEASE</version>
      </dependency>
      
    • 在SpringBoot中,会有网络安全拦截,去掉防止注销失败

      //防止网站工具 get,post
      http.csrf().disable(); //注销失败的原因就是这个
      





3. 记住我及首页定制

  • 记住我功能

    //开启记住我功能 cookie的实现 默认保存两周
    http.rememberMe();
    
  • 首页定制

    • 自定义登录页面

      //没有权限默认会到登录页面,需要开启登录的页面
      http.formLogin().loginPage("/toLogin");
      
    • 前端改一下不然登录失败,因为原来的/login是系统给配的

      <form th:action="@{/toLogin}" method="post">
      
    • 自定义记住我

      //开启记住我功能 cookie的实现 默认保存两周,自定义接受前端参数
      http.rememberMe().rememberMeParameter("remember");
      
    • 前端改一下样式

      </div >
      <div class="field">
          <input type="checkbox" name="remember"> 记住我
      </div>
      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值