SpringSecurity介绍

Spring Security 是针对 Spring 项目的安全框架,也是 Spring Boot 底层安全模块默认的技术选型。它可以实现强大的 Web 安全控制。对于安全控制吧,我们仅如引入 Security 场景启动器,进行少量配置,即可实现强大的安全管理。

应用程序安全的主要两个区域就是“认证”和“授权”:

  • 认证(Authentication):建立一个声明主体的过程,主体一般是指用户。
  • 授权(Authorization):指确定一个主体是否允许在你的应用程序执行一个动作的过程。

SpringSecurity with Boot 快速开始 | SpringSecurity 官方文档

整合SpringSecurity

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

1、使用 maven 新建 SpringBoot 项目,引入 Web、Thymeleaf、Security 场景启动器,依赖如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>1.5.19.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>zze.spring</groupId>
  12. <artifactId>security</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>security</name>
  15. <description>Demo project for Spring Boot</description>
  16.  
  17. <properties>
  18. <java.version>1.8</java.version>
  19. <!--修改 thymeleaf 依赖版本为 3 -->
  20. <thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
  21. <thymeleaf-layout-dialect.version>2.4.1</thymeleaf-layout-dialect.version>
  22. <thymeleaf-extras-springsecurity4.version>3.0.2.RELEASE</thymeleaf-extras-springsecurity4.version>
  23. </properties>
  24.  
  25. <dependencies>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-security</artifactId>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  33. </dependency>
  34. <dependency>
  35. <groupId>org.springframework.boot</groupId>
  36. <artifactId>spring-boot-starter-web</artifactId>
  37. </dependency>
  38.  
  39. <dependency>
  40. <groupId>org.springframework.boot</groupId>
  41. <artifactId>spring-boot-starter-test</artifactId>
  42. <scope>test</scope>
  43. </dependency>
  44. <dependency>
  45. <groupId>org.springframework.security</groupId>
  46. <artifactId>spring-security-test</artifactId>
  47. <scope>test</scope>
  48. </dependency>
  49. <!--thymeleaf 模板中使用 springsecurity 标签-->
  50. <dependency>
  51. <groupId>org.thymeleaf.extras</groupId>
  52. <artifactId>thymeleaf-extras-springsecurity4</artifactId>
  53. </dependency>
  54. </dependencies>
  55.  
  56. <build>
  57. <plugins>
  58. <plugin>
  59. <groupId>org.springframework.boot</groupId>
  60. <artifactId>spring-boot-maven-plugin</artifactId>
  61. </plugin>
  62. </plugins>
  63. </build>
  64.  
  65. </project>

pom.xml

2、编写测试模板页:

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org"
  3. xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
  4. <head>
  5. <meta charset="UTF-8">
  6. <title>首页</title>
  7. </head>
  8. <body>
  9. <div sec:authorize="!isAuthenticated()">
  10. <a th:href="@{/login}">请登录</a>
  11. </div>
  12. <div sec:authorize="isAuthenticated()">
  13. <span sec:authentication="name"/> 您好,您拥有角色:<span sec:authentication="principal.authorities"/>
  14. <form th:action="@{/logout}" method="post">
  15. <input type="submit" value="注销">
  16. </form>
  17. </div>
  18. <div sec:authorize="hasRole('VIP1')"><a th:href="@{/level/1}">LEVEL 1</a></div>
  19. <div sec:authorize="hasRole('VIP2')"><a th:href="@{/level/2}">LEVEL 2</a></div>
  20. <div sec:authorize="hasRole('VIP3')"><a th:href="@{/level/3}">LEVEL 3</a></div>
  21. </body>
  22. </html>

templates/welcome.html

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>登录页</title>
  6. </head>
  7. <body>
  8. <form th:action="@{/login}" method="post" >
  9. 用户名:<input type="text" name="username"> <br>
  10. 密码:<input type="text" name="password"> <br>
  11. <input type="checkbox" name="rememberMe">
  12. <input type="submit" value="登录"/>
  13. </form>
  14.  
  15. </body>
  16. </html>

templates/login.html

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>级别</title>
  6. </head>
  7. <body>
  8. <a th:href="@{/}">首页</a>
  9.  
  10. <h1 th:text="${level}"></h1>
  11. </body>
  12. </html>

templates/pages/level.html

3、编写测试 Controller:

  1. package zze.spring.security.controller;
  2.  
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.ui.Model;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.PathVariable;
  7.  
  8. @Controller
  9. public class TestController {
  10. private final String PREFIX = "pages/";
  11.  
  12. // 欢迎页
  13. @GetMapping("/")
  14. public String index() {
  15. return "welcome";
  16. }
  17.  
  18. @GetMapping("/level/{level}")
  19. public String level(@PathVariable Integer level, Model model) {
  20. model.addAttribute("level", level == 1 ? "初级" : level == 2 ? "中级" : "高级");
  21. return PREFIX + "level";
  22. }
  23.  
  24. @GetMapping("/login")
  25. public String login(){
  26. return "login";
  27. }
  28. }

zze.spring.security.controller.TestController

4、配置:

  1. package zze.spring.security.config;
  2.  
  3. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  4. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  5. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  6. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  7.  
  8. /**
  9. * 编写配置类继承 WebSecurityConfigurerAdapter
  10. */
  11. @EnableWebSecurity // 启用 WebSecurity 模式
  12. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  13.  
  14. /**
  15. * 控制请求的访问权限
  16. */
  17. @Override
  18. protected void configure(HttpSecurity http) throws Exception {
  19. // super.configure(http);
  20. // 定制请求的授权规则
  21. http.authorizeRequests().antMatchers("/").permitAll() // "/" 允许任何人访问
  22. .antMatchers("/level/1").hasRole("VIP1") // "/level/1" 仅允许拥有角色 VIP1 的主体访问
  23. .antMatchers("/level/2").hasRole("VIP2") // "/level/2" 仅允许拥有角色 VIP2 的主体访问
  24. .antMatchers("/level/3").hasRole("VIP3"); // "/level/3" 仅允许拥有角色 VIP3 的主体访问
  25.  
  26. // 开启自动配置的登录功能,开启后未登录状态访问将会自动重定向到 /login 登录页
  27. // 1、访问 /login 来到登录页
  28. // 2、重定向到 /login?error 表示登录失败
  29. // 3、可通过 loginPage() 方法修改使用自己的登录页,登录请求需要为 post,的用户名参数默认为 username ,密码参数为 password 。
  30. // 4、如果使用了 loginPage() 方法修改了登录页,那么该请求的 post 方式就是登录请求。比如修改 /userLogin 为登录页,那么 post 请求 /userLogin 则是登录操作
  31. http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/login");
  32.  
  33. // 开启自动配置的注销
  34. // 1、访问 /logout 表示用户注销,情况 session
  35. // 2、注销成功默认会重定向到 /login?logout
  36. //
  37. // 通过 logoutSuccessUrl("/") 方法指定注销成功重定向的页面
  38. http.logout().logoutSuccessUrl("/");
  39.  
  40. // 开启记住我功能
  41. // 1、登录成功后,将 cookie 发送给浏览器保存,以后访问都会带上这个 cookie,通过检查就可以免登录
  42. // 2、点击注销会删除 cookie
  43. // 3、可通过 rememberMeParameter 方法定义登录操作的记住我参数名
  44. http.rememberMe().rememberMeParameter("rememberMe");
  45. }
  46.  
  47. // 定义认证规则
  48. @Override
  49. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  50. // super.configure(auth);
  51. auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("VIP1", "VIP2") // 内存中存入一个用户(主体),用户名为 zhangsan 密码为 123456,拥有角色 VIP1 和 VIP2
  52. .and()
  53. .withUser("lisi").password("123456").roles("VIP2", "VIP3") // 内存中存入一个用户(主体),用户名为 lisi 密码为 123456,拥有角色 VIP2 和 VIP3
  54. .and()
  55. .withUser("wangwu").password("123456").roles("VIP1", "VIP3"); // 内存中存入一个用户(主体),用户名为 wangwu 密码为 123456,拥有角色 VIP1 和 VIP3
  56. }
  57. }

zze.spring.security.config.SecurityConfig

java框架之SpringBoot(15)-安全及整合SpringSecurity的更多相关文章

  1. java框架之SpringBoot(16)-分布式及整合Dubbo

    前言 分布式应用 在分布式系统中,国内常用 Zookeeper + Dubbo 组合,而 SpringBoot 推荐使用 Spring 提供的分布式一站式解决方案 Spring + SpringBoo ...

  2. java框架之SpringBoot(12)-消息及整合RabbitMQ

    前言 概述 大多数应用中,可通过消息服务中间件来提升系统异步通信.扩展解耦的能力. 消息服务中两个重要概念:消息代理(message broker)和目的地(destination).当消息发送者发送 ...

  3. java框架之SpringBoot(13)-检索及整合Elasticsearch

    ElasticSearch介绍 简介 我们的应用经常需要使用检索功能,开源的 Elasticsearch 是目前全文搜索引擎的首选.它可以快速的存储.搜索和分析海量数据.SpringBoot 通过整合 ...

  4. (七) SpringBoot起飞之路-整合SpringSecurity(Mybatis、JDBC、内存)

    兴趣的朋友可以去了解一下前五篇,你的赞就是对我最大的支持,感谢大家! (一) SpringBoot起飞之路-HelloWorld (二) SpringBoot起飞之路-入门原理分析 (三) Sprin ...

  5. 【SpringBoot】Springboot2.x整合SpringSecurity

    一.Spring Security是什么?有什么作用(核心作用)?以及如何阅读本篇文章 1.是什么 Spring Security是Spring家族的一个强大的安全框架,与Springboot整合的比 ...

  6. java框架之SpringBoot(9)-数据访问及整合MyBatis

    简介 对于数据访问层,无论是 SQL 还是 NOSQL,SpringBoot 默认采用整合 SpringData 的方式进行统一处理,添加了大量的自动配置,引入了各种 Template.Reposit ...

  7. 【java框架】SpringBoot(5)--SpringBoot整合分布式Dubbo+Zookeeper

    1.理论概述 1.1.分布式 分布式系统是若干独立计算机的集合,这些计算机对于用户来讲就像单个系统. 由多个系统集成成一个整体,提供多个功能,组合成一个板块,用户在使用上看起来是一个服务.(比如淘宝网 ...

  8. java框架之SpringBoot(11)-缓存抽象及整合Redis

    Spring缓存抽象 介绍 Spring 从 3.1 版本开始定义了 org.springframework.cache.Cache 和 org.springframework.cache.Cache ...

  9. 【java框架】SpringBoot(7) -- SpringBoot整合MyBatis

    1.整合MyBatis操作 前面一篇提到了SpringBoot整合基础的数据源JDBC.Druid操作,实际项目中更常用的还是MyBatis框架,而SpringBoot整合MyBatis进行CRUD也 ...

随机推荐

  1. 转:图像处理、显示中的行宽(linesize)、步长(stride)、间距(pitch)

    在图像数据传输和显示的过程中有一个不常用的参数:间距. 间距的名称: 它有很多的别名,在使用d3d显示的时候,它叫pitch:在用ffmpeg解码的时候,它叫linesize: 在用ffmpeg转换格 ...

  2. 20款最好的JavaScript开发框架

    JavaScript语言有多种方式,创建交互式网站,Web应用程序.基本的JavaScript框架是预先写好的JavaScript代码集.这些JavaScript框架也被称为JavaScript库,开 ...

  3. 【gulp】gulp + browsersync 构建前端项目自动化工作流

    什么是 gulp? gulp.js 是一个自动化构建工具,开发者可以使用它在项目开发过程中自动执行常见任务.gulp.js 是基于 node.js 构建的,利用 node.js 流的威力,你可以快速构 ...

  4. jenkins GitHub 自动触发

    jenkins GitHub 自动触发 转载请注明出处: 转载自Bin's Blog:  jenkins GitHub 自动触发( http://www.wenbin.cf/post/54/ ) 需要 ...

  5. Android 8 蓝牙 A2DP流程

    记录一下蓝牙A2DP的流程 packages\apps\Settings\src\com\android\settings\bluetooth\BluetoothPairingDetail.java ...

  6. CentOS7安装Java还是无法使用javac

    centos7.4 安装java之后,还是无法使用javac命令.报错提示: [root@ip---- centos]# javac bash: javac: command not found 解决 ...

  7. redis服务器学习一

    一:什么是redis服务器 redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合).zs ...

  8. [Vue warn]: Attribute "id" is ignored on component <div> because the component is a fragment instanc

    今天在使用vue框架搭建环境时,遇到这个错误提示: [Vue warn]: Attribute "id" is ignored on component <div> b ...

  9. mongodb配置、启动、备份

    Mongodb: 启动: /usr/bin/mongod --config /data/mydata/mongodb/mongodb.conf 停止Mongodb: 方法一:$ mongod --sh ...

  10. Spark学习之常用算子介绍

    1. reduceByKey reduceByKey的作用对像是(key, value)形式的rdd,而reduce有减少.压缩之意,reduceByKey的作用就是对相同key的数据进行处理,最终每 ...