• SpringBoot-27-springSecurity(安全:认证授权)


    8.4 springSecurity(安全:认证授权)
    • Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。它是保护基于Spring的应用程序的事实标准。
    • Spring Security是一个专注于为Java应用程序提供身份验证和授权的框架。与所有Spring项目一样,Spring安全性的真正威力在于它可以多么容易地扩展以满足定制需求
    • Spring Security是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理!

    功能权限(管理员、普通用户)
    访问权限(页面访问)
    菜单权限

    • 若使用拦截器,过滤器也可以实现身份验证和授权功能但会产生大量的原生代码~冗余
    • 在web开发中,安全第一位!过滤器,拦截器做的好也可以不用springSecurity

    • 网站安全非功能性需求

    • 做网站:安全应该在什么时候考虑?设计之初!

      • 漏洞,隐私泄露~
      • 架构一旦确定,在加安全就会改动大量代码
    • 主流的安全框架shiro/SpringSecurity:二者很像~除了类不一样,名字不一样;做认证,授权(vip1,vip2,vip3)

    • 将拦截器、过滤器一路简化:MVC—SPRING—SPRINGBOOT—框架思想

    • 导依赖thymeleaf启动器

    
        org.springframework.boot
        spring-boot-starter-security
    
    
        org.springframework.boot
        spring-boot-starter-thymeleaf
    
    
        org.springframework.boot
        spring-boot-starter-web
    
    
    
        org.thymeleaf.extras
        thymeleaf-extras-springsecurity5
    
    
        org.springframework.boot
        spring-boot-devtools
        runtime
        true
    
    
    
        org.thymeleaf
        thymeleaf-spring5
        3.0.15.RELEASE
        compile
    
    
        org.thymeleaf.extras
        thymeleaf-extras-java8time
        3.0.4.RELEASE
        compile
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 记住几个类:

    WebSecurityConfigurerAdapter:自定义Security策略
    AuthenticationManagerBuilder:自定义认证策略
    @EnableWebSecurity:开启WebSecurity模式 、后续的springcloud中@Enablexxx开启某个功能

    • Spring Security的两个主要目标是“认证”和“授权”(访问控制)。

      • "认证”(Authentication)
      • “授权”(Authorization)
    • 这个概念是通用的,而不是只在Spring Security中存在。

    • 官网:https://spring.io/projects/spring-security/查看项目中的版本,找到对于的帮助文档。

    • 用例结构,静态资源或者是SpringBoot-27-springSecurity(安全:认证授权)demo的静态资源进行静态资源下载

    在这里插入图片描述

    • application.properties中关闭thymelea缓存
    spring.thymeleaf.cache=false
    
    • 1
    • 路由控制层RouterController
    package com.zk.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    /**
     * @author CNCLUKZK
     * @create 2022/8/3-22:32
     */
    @Controller
    public class RouterController {
    
        @RequestMapping({"/","/index","/index.html"})
        public String toIndex(){
            return "index";
        }
        @RequestMapping("/toLogin")
        public String toLogin(){
            return "views/login";
        }
        @RequestMapping("/level1/{id}")
        public String level1(@PathVariable("id") String id){
            return "views/level1/"+id;
        }
        @RequestMapping("/level2/{id}")
        public String level2(@PathVariable("id") String id){
            return "views/level2/"+id;
        }
        @RequestMapping("/level3/{id}")
        public String level3(@PathVariable("id") String id){
            return "views/level3/"+id;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 认证授权安全配置
    package com.zk.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.WebSecurityConfiguration;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    
    /**
     * @author CNCLUKZK
     * @create 2022/8/3-23:07
     */
    //AOP思想,非拦截器
    @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();
    
            http.httpBasic();
        }
    
        //认证规则,springboot2.1.X可以直接使用,认证用户和角色
        //密码编码:PasswordEncoder 缺少加密报错
        //spring Secutiry5.0+新增了很多的加密方法
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            //正常应该从数据库中读取
            auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("admin").password(new BCryptPasswordEncoder().encode("111111")).roles("vip1","vip2","vip3")
                    .and().withUser("zs").password(new BCryptPasswordEncoder().encode("111111")).roles("vip1")
                    .and().withUser("ls").password(new BCryptPasswordEncoder().encode("111111")).roles("vip2")
                    .and().withUser("ww").password(new BCryptPasswordEncoder().encode("111111")).roles("vip3");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 之后就可以访问http://127.0.0.1:8080/进行测试,发现admin用户登录的账号3种类型页面都能访问,其他的单一角色只能访问对应的页面

    在这里插入图片描述

    • 注意高版本springSecutiry5在登陆时需要对内存中密码进行加密,可以用springSecutiry提供的加密规则

    • JDBC Authentication链接数据库进行授权认证

    @Autowired
    private DataSource dataSource;
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)throws Exception
    /ensure the passwords are encoded properly
    UserBuilder users=User.withDefaultPasswordEncoder();
    auth.jdbcAuthentication().dataSource(dataSource).withDefaultSchema()
    .withUser(users.username("user").password("password").roles("USER"))
    .withUser(users.username("admin").password("password").roles("USER","ADMIN"));
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    下一篇:SpringBoot-28-springSecurity注销和权限控制
  • 相关阅读:
    面试准备2022-08
    SONAR自定义检查规则插件
    华为机试真题实战应用【算法代码篇】-最大嵌套括号深度(附Java、python和C++代码)
    全局的键盘监听事件
    springBoot全局异常定义
    “从根到叶:深入理解排序数据结构“
    Trie字典树
    YOLO_v6讲解
    php 二分查询算法实现
    【Java】Netty创建网络服务端客户端(TCP/UDP)
  • 原文地址:https://blog.csdn.net/weixin_42045639/article/details/126483601