SpringBoot之SpringSecurity(安全)

2023-05-16

SpringSecurity(安全)

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

记住几个类:

  • WebSecurityConfigurerAdapter:自定义Security策略
  • AuthenticationManagerBuilder:自定义认证策略
  • @EnableWebSecurity:开启WebSecurity模式

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

“认证”(Authentication)

身份验证是关于验证您的凭据,如用户名/用户ID和密码,以验证您的身份。

身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用。

“授权” (Authorization)

授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库,资金,位置,几乎任何内容)的完全权限。

这个概念是通用的,而不是只在Spring Security 中存在。

实验环境搭建

  1. 新建一个项目

    这里记得要选择thymeleaf

  2. 导入静态资源

    • 静态资源获取:https://gitee.com/ENNRIAAA/spring-security-material

      image-20220312193101453

  3. 创建路由RouterController跳转测试静态资源是否能够访问

    @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. 运行项目进行测试

认证和授权

  1. 导入依赖

    <!--        security-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    
  2. 编写SecurityConfig

    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        //授权
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            //首页所有人可以访问,功能页只有对应有权限的人才能访问
            http.authorizeHttpRequests()
                    .antMatchers("/").permitAll()
                    .antMatchers("/level1/**").hasRole("vip1")
                    .antMatchers("/level2/**").hasRole("vip2")
                    .antMatchers("/level3/**").hasRole("vip3");
            //没有权限会默认到登录页,需要开启登录的页面
            // /login
            http.formLogin();
    
            //防止网站攻击: get,post
            http.csrf().disable();//关闭csrf功能,登出失败可能存在的原因
    
    
            //注销,开启了注销功能,跳到首页
            http.logout().logoutSuccessUrl("/");
        }
    
        //认证
        //密码编码:PasswordEncoder
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            //这些数据正常应该从数据库中读
            auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("lzj").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");
    
        }
    }
    
  3. 测试

注销和权限控制

  1. 导入依赖

    <!--        security-thymeleaf整合包-->
            <dependency>
                <groupId>org.thymeleaf.extras</groupId>
                <artifactId>thymeleaf-extras-springsecurity5</artifactId>
                <version>3.0.4.RELEASE</version>
            </dependency>
    
  2. 注入命名空间

    xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
    
  3. 修改登录和注销按钮

    实现用户未登录时只显示登录,用户登录后显示用户名、角色和注销

    <!--登录注销-->
                <div class="right menu">
                    <!--如果未登录-->
                    <div sec:authorize="!isAuthenticated()">
                        <a class="item" th:href="@{/toLogin}">
                            <i class="address card icon"></i> 登录
                        </a>
                    </div>
    <!--                如果登录:用户名,注销-->
                    <div sec:authorize="isAuthenticated()">
                        <a class="item">
                            用户名:<span sec:authentication="name"></span>
                            角色:<span sec:authentication="authorities"></span>
                        </a>
                    </div>
                    <div sec:authorize="isAuthenticated()">
                        <a class="item" th:href="@{/logout}">
                            <i class="sign-out icon"></i> 注销
                        </a>
                    </div>
    
                    <!--已登录
                    <a th:href="@{/usr/toUserCenter}">
                        <i class="address card icon"></i> admin
                    </a>
                    -->
                </div>
    
  4. 修改用户的权限显示

    <!--            菜单根据用户的角色动态实现-->
                <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 class="ui raised segment">
                        <div class="ui">
                            <div class="content">
                                <h5 class="content">Level 2</h5>
                                <hr>
                                <div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
                                <div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
                                <div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
                            </div>
                        </div>
                    </div>
                </div>
    
                <div class="column" sec:authorize="hasRole('vip3')">
                    <div class="ui raised segment">
                        <div class="ui">
                            <div class="content">
                                <h5 class="content">Level 3</h5>
                                <hr>
                                <div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
                                <div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
                                <div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
                            </div>
                        </div>
                    </div>
                </div>
    
  5. 测试

记住我和首页定制

可以使用我们自己的登录页登录

  1. 编写SecurityConfig

    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        //授权
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            //首页所有人可以访问,功能页只有对应有权限的人才能访问
            http.authorizeHttpRequests()
                    .antMatchers("/").permitAll()
                    .antMatchers("/level1/**").hasRole("vip1")
                    .antMatchers("/level2/**").hasRole("vip2")
                    .antMatchers("/level3/**").hasRole("vip3");
            //没有权限会默认到登录页,需要开启登录的页面
            // /login
            //定制根页面,user为表单中username的name,pwd为表单中password的name
            //loginProcessingUrl为表单跳转路径,若无这个,则跳转路径为toLogin
            http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");
    
            //防止网站攻击: get,post
            http.csrf().disable();//关闭csrf功能,登出失败可能存在的原因
    
            //注销,开启了注销功能,跳到首页
            http.logout().logoutSuccessUrl("/");
    
            //开启记住我功能   cookie  默认保存时间14//自定义接收前端参数,remember为表单中的名字
            http.rememberMe().rememberMeParameter("remember");
        }
    
        //认证
        //密码编码:PasswordEncoder
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            //这些数据正常应该从数据库中读
            auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("lzj").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. 修改登录页面表单

    <form th:action="@{/login}" method="post">
        <div class="field">
            <label>Username</label>
            <div class="ui left icon input">
                <input type="text" placeholder="Username" name="user">
                <i class="user icon"></i>
            </div>
        </div>
        <div class="field">
            <label>Password</label>
            <div class="ui left icon input">
                <input type="password" name="pwd">
                <i class="lock icon"></i>
            </div>
        </div>
        <div class="field">
            <input type="checkbox" name="remember">记住我
        </div>
    
        <input type="submit" class="ui blue submit button"/>
    </form>
    
  3. 测试
    input type=“password” name=“pwd”>




    记住我

    <input type="submit" class="ui blue submit button"/>
    
    ```
  4. 测试

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringBoot之SpringSecurity(安全) 的相关文章

随机推荐

  • 树莓派3B+raspbian+docker+hassio安装教程

    说明 1 此文转载 侵删 参考https bbs hassbian com thread 3501 1 1 html 2 修改echo 34 96 date 43 H M S 96 gt gt gt gt gt gt gt gt gt gt
  • Linux - 开机启动流程

    目录 一 掌握开机启动流程的意义 xff1a 1 1 为什么需要了解开机启动流程 xff1f 1 2 在日常的运维过程中 xff0c 是否会遇到机器出现问题启动不了 xff1f 1 3 开机启动流程的意义 二 开机启动流程 2 1 开机启动
  • 关于Ubuntu中出现:Unable to fetch some archives, maybe run apt-get update or try with --fix-missing问题

    在Ubuntu有网络的情况下 xff0c 如果出现在进行 apt update或者apt install时 xff0c 出现Unable to fetch some archives maybe run apt get update or
  • 2022年宜春市职业院校技能大赛中职组“网络搭建与应用”赛项任务书

    2022年宜春市职业院校技能大赛中职组 网络搭建与应用 赛项任务书 xff08 总分1000分 xff09 赛题说明 一 竞赛内容分布 网络搭建与应用 竞赛共分二个部分 xff0c 其中 xff1a 第一部分 xff1a 网络搭建及安全部署
  • Java之变量的作用域和初始化

    write xff1a 2022 4 28 前文我们学习了Java的数据类型 xff1a Java之数据类型 xff0c 本文我们学习变量的作用域和初始化 xff0c 文中有大量使用实例讲解分析 xff0c 需耐心解读代码 文章目录 1 变
  • springboot集成mybatis:查询数据库,返回的结果为null的解决办法

    springboot集成mybatis xff1a 查询数据库 xff0c 返回的结果为null的解决办法 问题重现 xff1a 数据库中的数据 查询的结果 xff1a 也就是说我数据库中有几个数据就有几个null值 这就很奇怪了 xff0
  • springboot使用thymeleaf后找不到模板(五个细节)已解决

    问题 xff1a springboot使用thymeleaf模板后找不到html模板 第一种情况 xff1a 先说第一种情况 xff0c 也是我出现问题的原因 xff1a 那就是导入thymeleaf的命名空间后 xff0c 粗心大意的将t
  • 一篇实现springboot集成elasticsearch的增删改查

    准备工作 springboot版本 span class token generics span class token punctuation lt span parent span class token punctuation gt
  • centos7连接不上网络,保姆级演示,亲测,亲测

    centos连接网络无非就大 五步 写在前边 xff1a vmware16 centos7 1 打开vm xff1a 编辑 虚拟网络编辑器 更改设置 2 有三个网络名称 VMnet0 xff1a 选择仅主机模式 xff0c 勾选下边两个选项
  • 简单三步,实现idea远程debug

    远程debug xff0c 简单三步 这里默认你已经打好了jar包 第一步 xff0c 编辑idea配置 1 1 点击edit configurations 1 2 点击 43 号选择Remote JVM Debug 1 3 进行配置 xf
  • shell把变量的值作为变量使用

    有那么一种生产环境 我有一个变量 xff0c 变量有一个初始值比如count 61 1 我想将count计算或者处理后的值再次作为参数传递 举个例子 span class token assign left variable name sp
  • lamp配置

    lamp独立配置 简介 所谓lamp xff0c 其实就是由Linux 43 Apache 43 Mysql MariaDB 43 Php Perl Python的一组动态网站或者服务器的开源软件 xff0c 除Linux外其它各部件本身都
  • Archlinux系统屏幕花屏

    我的电脑 xff0c 联想Y7000 xff0c 2019款 xff0c Archlinux内核版本 xff0c 系统情况如下 花屏样例 xff0c 这只是其中一种花屏样式 xff0c 屏幕一直不受控制的在闪动 出现这种情况不难猜到是显卡驱
  • centos7 使用letsEncrypt certbot 生成免费的ssl证书 渐进学习

    1 我们将会使用letsencrypt证书颁发机构里的certbot客户端 certbot官网 xff0c 国内也可访问 https certbot eff org 2 准备工作 xff0c 这一步很重要 你首先需要有一个解析通过了的域名
  • CSS选择器

    c选择器表示要定义样式的对象 xff0c 可以是元素本身 xff0c 也可以是一类元素或者指定名称的元素 一 选择器的分类 1 元素选择器 xff1a 以标签名作为选择器的一种方式 xff0c 例如 xff1a p h1 h6 div ul
  • 多生产者多消费者解决方式

    在上一篇博客中记录了如何解决普通生产者消费者的问题 xff0c 这篇讲一下如何解决多生产者多消费者问题 多生产者多消费者问题案例 xff1a 一家四口围着一个盘子 xff0c 盘子中最多放两个水果 爸爸不断向盘子中投放苹果 xff0c 儿子
  • 关于Java NoSuchElementException: No value present以及java.lang.NullPointerException处理

    1 Java NoSuchElementException No value present while curSum lt 100 找出小数余额最大的组 xff0c 对其进行加1 CircleRequest max 61 list str
  • 手机号无法验证,如何注册推特

    Twitter无法添加 验证中国手机号码 xff1f 既然Twitter无法添加 验证中国手机号码 xff0c 怎么解冻呢 xff1f 以下是推特注册时 xff0c 验证 43 86手机号解决方法 xff1a 进入账号申诉页面 点此进入 T
  • vue安装vue-router出错

    项目场景 xff1a 在vue中安装vue router 问题描述 xff1a 提示 xff1a 在安装过程中报错 xff0c 缺少依赖 xff1a PS D span class token punctuation span WebDep
  • SpringBoot之SpringSecurity(安全)

    SpringSecurity xff08 安全 xff09 Spring Security是针对Spring项目的安全框架 xff0c 也是Spring Boot底层安全模块默认的技术选型 xff0c 他可以实现强大的Web安全控制 xff