SpringBoot1.x 安全

文章源码

环境搭建

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

登录 注销 认证 授权 权限控制

应用程序的两个主要区域是 “认证”“授权(或者访问控制)”。这两个主要区域是 SpringSecurity 的两个目标。

通过继承 WebSecurityConfigurerAdapter,可以自定义 Security 策略。使用 @EnableWebSecurity,开启 WebSecurity 模式。

“认证”(Authentication),是建立一个它声明的主体的过程(一个“主体”一般是指用户,设备或一些可以在你的应用程序中执行动作的其他系统)。

“授权”(Authorization),指确定一个主体是否允许在你的应用程序执行一个动作的过程。为了抵达需要授权的点,主体的身份已经由认证过程建立。

Thymeleaf 提供的 SpringSecurity 标签支持,需要引入依赖:

        <!-- Thymeleaf 提供的 SpringSecurity 标签支持 -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>

  • 首页 welcome.html

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org"
    xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <h1 align="center">欢迎光临武林秘籍管理系统</h1>
    <div sec:authorize="!isAuthenticated()">
    <h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/userlogin}">请登录</a> </h2>
    </div>
    <div sec:authorize="isAuthenticated()">
    <h2 th:align="center">用户:<span sec:authentication="name"></span>,角色:<span sec:authentication="principal.authorities"></span></h2>
    <form th:align="center" th:action="@{/logout}" method="post">
    <input type="submit" value="注销">
    </form>
    </div> <hr> <div sec:authorize="hasRole('VIP1')">
    <h3>普通武功秘籍</h3>
    <ul>
    <li><a th:href="@{/level1/1}">罗汉拳</a></li>
    <li><a th:href="@{/level1/2}">武当长拳</a></li>
    <li><a th:href="@{/level1/3}">全真剑法</a></li>
    </ul>
    </div> <div sec:authorize="hasRole('VIP2')">
    <h3>高级武功秘籍</h3>
    <ul>
    <li><a th:href="@{/level2/1}">太极拳</a></li>
    <li><a th:href="@{/level2/2}">七伤拳</a></li>
    <li><a th:href="@{/level2/3}">梯云纵</a></li>
    </ul>
    </div> <div sec:authorize="hasRole('VIP3')">
    <h3>绝世武功秘籍</h3>
    <ul>
    <li><a th:href="@{/level3/1}">葵花宝典</a></li>
    <li><a th:href="@{/level3/2}">龟派气功</a></li>
    <li><a th:href="@{/level3/3}">独孤九剑</a></li>
    </ul>
    </div> </body>
    </html>
  • 登录页 login.html

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <h1 align="center">欢迎登陆武林秘籍管理系统</h1>
    <hr>
    <div align="center">
    <form th:action="@{/userlogin}" method="post">
    用户名:<input name="user"/><br>
    密码:<input name="pwd"><br/>
    <input type="checkbox" name="remember"> 记住我 <br>
    <input type="submit" value="登陆">
    </form>
    </div>
    </body>
    </html>
  • 自定义安全配置类 CustomSecurityConfig.java

    /**
    * @Author : parzulpan
    * @Time : 2021-01
    * @Desc : 自定义安全配置类
    */ @EnableWebSecurity // 开启 WebSecurity 模式
    public class CustomSecurityConfig 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"); // 开启自动配置的登录功能,如果没有登录或者没有权限就会来到登录页面
    // 1. 访问 /login 来到登录页
    // 2. 重定向到 login?error 表示登录失败
    // 3. ...
    // http.formLogin(); // 指定自定义的登录页
    // 1. 默认 post 形式,/login 代表处理登录
    // 2. 一旦定制 loginPage,那么 loginPage 的 post 请求就是登录
    http.formLogin().usernameParameter("user").passwordParameter("pwd")
    .loginPage("/userlogin"); // 关闭 CSRF(Cross-site request forgery)跨站请求伪造
    // http.csrf().disable(); // 开启自动配置的注销功能
    // 1. 访问 /logout 表示用户注销,清空 session
    // 2. 注销成功,会自动重定向到 login?logout
    // 3. logoutSuccessUrl 注销成功,自动回到首页
    http.logout().logoutSuccessUrl("/"); // 开启记住我功能
    // 1. 登录成功以后,将 cookie 发给浏览器保存,以后访问页面会带上这个 cookie,只要通过检查就可以免登录
    // 2. 点击注销就会删除 cookie
    http.rememberMe().rememberMeParameter("remember"); } // 定制认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
    .withUser("User01").password("123456").roles("VIP1", "VIP2")
    .and()
    .withUser("User02").password("123456").roles("VIP2", "VIP3")
    .and()
    .withUser("User03").password("123456").roles("VIP3", "VIP1");
    }
    }
  • 书籍控制类 KungfuController.java

    /**
    * @Author : parzulpan
    * @Time : 2021-01
    * @Desc : 书籍控制类
    */ @Controller
    public class KungfuController {
    private final String PREFIX = "pages/"; /**
    * 欢迎页
    * @return
    */
    @GetMapping("/")
    public String index() {
    return "welcome";
    } /**
    * 登陆页
    * @return
    */
    @GetMapping("/userlogin")
    public String loginPage() {
    return PREFIX+"login";
    } /**
    * level1页面映射
    * @param path
    * @return
    */
    @GetMapping("/level1/{path}")
    public String level1(@PathVariable("path")String path) {
    return PREFIX+"level1/"+path;
    } /**
    * level2页面映射
    * @param path
    * @return
    */
    @GetMapping("/level2/{path}")
    public String level2(@PathVariable("path")String path) {
    return PREFIX+"level2/"+path;
    } /**
    * level3页面映射
    * @param path
    * @return
    */
    @GetMapping("/level3/{path}")
    public String level3(@PathVariable("path")String path) {
    return PREFIX+"level3/"+path;
    }
    }

总结和练习

【SpringBoot1.x】SpringBoot1.x 安全的更多相关文章

  1. 记 SpringBoot1.* 转 Springoot2.0 遇到的问题

    1.拦截器问题 到2.0之后在配置文件中写 static-path-pattern: /static/** 已经不起作用(2.0需要在方法中配置) SpringBoot1.*写法 @Configura ...

  2. SpringBoot1.x与监控(六)

    由于2.x和1.x的监控不一样,此处先讲1.x 一 SpringBoot1.x监控 pom.xml <dependency> <groupId>org.springframew ...

  3. SpringBoot1.x升级SpringBoot2.x踩坑之文件上传大小限制

    SpringBoot1.x升级SpringBoot2.x踩坑之文件上传大小限制 前言 LZ最近升级SpringBoo框架到2.1.6,踩了一些坑,这里介绍的是文件上传大小限制. 升级前 #文件上传配置 ...

  4. 使用SpringBoot1.4.0的一个坑

    时隔半年,再次使用Spring Boot快速搭建微服务,半年前使用的版本是1.2.5,如今看官网最新的release版本是1.4.0,那就用最新的来构建,由于部署环境可能有多套所以使用maven-fi ...

  5. springboot1.5和jpa利用HikariCP实现多数据源的使用

    背景 现在已有一个完整的项目,需要引入一个新的数据源,其实也就是分一些请求到从库上去 技术栈 springboot1.5 (哎,升不动啊) 思路 两个数据源,其中一个设置为主数据源 两个事物管理器,其 ...

  6. 【SpringBoot1.x】SpringBoot1.x 开发热部署和监控管理

    SpringBoot1.x 开发热部署和监控管理 热部署 在开发中我们修改一个 Java 文件后想看到效果不得不重启应用,这导致大量时间花费,我们希望不重启应用的情况下,程序可以自动部署(热部署). ...

  7. 【SpringBoot1.x】SpringBoot1.x 分布式

    SpringBoot1.x 分布式 分布式应用 Zookeeper&Dubbo ZooKeeper 是用于分布式应用程序的高性能协调服务.它在一个简单的界面中公开了常见的服务,例如命名,配置管 ...

  8. 【SpringBoot1.x】SpringBoot1.x 任务

    SpringBoot1.x 任务 文章源码 异步任务 在 Java 应用中,绝大多数情况下都是通过同步的方式来实现交互处理的.但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使 ...

  9. 【SpringBoot1.x】SpringBoot1.x 检索

    SpringBoot1.x 检索 文章源码 概念 Elasticsearch 是一个分布式的开源搜索和分析引擎,适用于所有类型的数据,包括文本.数字.地理空间.结构化和非结构化数据.Elasticse ...

随机推荐

  1. EF 查询外键对应的实例

    EF 查询外键对应的实例   1. 查询时易遇到的情况: 能查询到外键值,但对应的外键实例为null. 解决方法: (1) 使用EF的include // 我的应用如下 // SampleResult ...

  2. 史上最全单链表的增删改查反转等操作汇总以及5种排序算法(C语言)

    目录 1.准备工作 2.创建链表 3.打印链表 4.在元素后面插入元素 5.在元素前面增加元素 6.删除链表元素,要注意删除链表尾还是链表头 7.根据传入的数值查询链表 8.修改链表元素 9.求链表长 ...

  3. Docker(二):Docker镜像仓库Harbor搭建

    安装docker-compose 因为docker-compose下载容易失败, 所以选择从github下载方式安装. [root@harbor ~]# mv docker-compose-Linux ...

  4. idea 最好用的插件

    1.lombok 不用写get,set方法 2.MyBatisCodeHelperPro 3.Rainbow Brackets 彩虹括号 5.activate-power-mode 动感打字 7.Ba ...

  5. glances linux资源使用监控

    安装 yum install glances -y 界面 介绍 命令选项 -b:显示网络连接速度 Byte/ 秒 -B @IP|host :绑定服务器端 IP 地址或者主机名称 -c @IP|host ...

  6. 面试 15-虚拟DOM

    15-虚拟DOM #前言 vdom 是 vue 和 React 的核心,先讲哪个都绕不开它. vdom 比较独立,使用也比较简单. 如果面试问到 vue 和 React 和实现,免不了问 vdom: ...

  7. js下 Day13、面向对象

    一.对象 什么是对象: 一组无序的属性集合 创建对象两种方式: 对象字面量: var obj = {} 实例化: var obj = new Object() 对象取值: **[] ( ** 中括号) ...

  8. C#爬虫,让你不再觉得神秘

    1.使用第三方类库 HtmlAgilityPack 官方网址:https://html-agility-pack.net/?z=codeplex. // From File 从文件获取html信息 v ...

  9. 最新 obs-studio vs2019 开发环境搭建 代码编译

    距离上一篇文章很久了,重新开始记录 OBS 开发相关情况,第一步就是环境搭建,第二步是构建 OBS-Studio VS 2019 开发环境搭建 下载软件和资源 软件安装没有特别说明的,下载安装即可. ...

  10. C# 生成6位短信验证码

    1 private string VerifyCode() 2 { 3 Random random = new Random(); 4 return random.Next(100000, 99999 ...