一、安全简介
在 Web 开发中,安全一直是非常重要的一个方面。安全虽然属于应用的非功能性需求,但是应该在应用开发的初期就考虑进来。
市面上存在比较有名的:Shiro,Spring Security !
Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。它实际上是保护基于spring的应用程序的标准。
Spring Security是一个框架,侧重于为Java应用程序提供身份验证和授权。与所有Spring项目一样,Spring安全性的真正强大之处在于它可以轻松地扩展以满足定制需求。
Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理。使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。
二、SpringBoot集成SpringSecurity
1、实验环境搭建
1、新建一个初始的springboot项目的web模块,thymeleaf模块
<!-- thymeleaf模板 --><dependency><groupId>org.thymeleaf</groupId><artifactId>thymeleaf-spring5</artifactId></dependency><dependency><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-java8time</artifactId></dependency>
2、导入静态资源
templatesviewslevel11.html2.html3.htmllevel21.html2.html3.htmllevel31.html2.html3.htmllogin.htmlindex.html
3、controller跳转!
@Controllerpublic 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、测试实验环境是否OK!
2、认识SpringSecurity
Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理!
记住几个类:
- WebSecurityConfigurerAdapter:自定义Security策略
- AuthenticationManagerBuilder:自定义认证策略
- @EnableWebSecurity:开启WebSecurity模式
Spring Security的两个主要目标是 “认证” 和 “授权”(访问控制)。
“认证”(Authentication)
身份验证是关于验证您的凭据,如用户名/用户ID和密码,以验证您的身份。
身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用。
“授权” (Authorization)
授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库,资金,位置,几乎任何内容)的完全权限。
这个概念是通用的,而不是只在Spring Security 中存在。
3、认证和授权
目前,我们的测试环境,是谁都可以访问的,我们使用 Spring Security 增加上认证和授权的功能
1、引入 Spring Security 模块
<!-- security --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>
2、编写 Spring Security 配置类
查看我们自己项目中的版本,在官网找到对应的帮助文档:
3、编写基础配置类
@EnableWebSecurity // 开启WebSecurity模式public class SecurityConfig extends WebSecurityConfigurerAdapter {// 链式编程@Overrideprotected void configure(HttpSecurity http) throws Exception {// 首页所有人都可以访问, 功能页只有对应有权限的人才能访问// 请求授权的规则~http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/level1/**").hasRole("vip1").antMatchers("/level2/**").hasRole("vip2").antMatchers("/level3/**").hasRole("vip3");// 没有权限的默认会到登录页面,需要开启登录的页面// login// http.formLogin(); // 跳转到自带的登录页面http.formLogin().loginPage("/toLogin"); // 跳转到自己定制的登录页面// 注销,开启了注销功能,跳转首页// 防止网络工具 : get, posthttp.csrf().disable(); // 关闭csrf功能(跨站域请求伪造)http.logout().logoutSuccessUrl("/");// 开启记住我功能// http.rememberMe();http.rememberMe().rememberMeParameter("remember");}// 认证, springboot 2.1.x 可以直接使用// 密码编码: BCryptPasswordEncoder// 在Spring Secutiry 5.0+ 新增了很多的加密方法@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {// 在内存用验证用户信息// 在数据库中验证用户信息 auth.jdbcAuthentication()auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("shuai").password(new BCryptPasswordEncoder().encode("shuai")).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");}}
4、前端页面,我们需要结合thymeleaf中的一些功能
Maven依赖:
<!-- thymeleaf模板 --><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.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-springsecurity4</artifactId><version>3.0.4.RELEASE</version></dependency>
index.html
命名空间
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
<div class="ui secondary menu"><a class="item" th:href="@{/index}">首页</a><!--登录注销--><div class="right menu"><!--sec:authorize 需要导入命名空间--><!--如果未登录--><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></a></div><div sec:authorize="isAuthenticated()"><a class="item" th:href="@{/logout}"><i class="sign-out icon"></i> 注销</a></div></div></div>
注意:login.html中的用户名和密码默认是name=”username”和name=”password”,如果写成name或者是pwd的话,需要更改定制登录页面为usernameParameter(“name”),不然会报错。
三、SpringBoot集成shiro
1、认识Shiro
主要功能
三个核心组件:Subject, SecurityManager 和 Realms.
Subject:即“当前操作用户”。但是,在Shiro中,Subject这一概念并不仅仅指人,也可以是第三方进程、后台帐户(Daemon Account)或其他类似事物。它仅仅意味着“当前跟软件交互的东西”。
Subject代表了当前用户的安全操作,SecurityManager则管理所有用户的安全操作。
SecurityManager:它是Shiro框架的核心,典型的Facade模式,Shiro通过SecurityManager来管理内部组件实例,并通过它来提供安全管理的各种服务。
Realm: Realm充当了Shiro与应用安全数据间的“桥梁”或者“连接器”。也就是说,当对用户执行认证(登录)和授权(访问控制)验证时,Shiro会从应用配置的Realm中查找用户及其权限信息。
从这个意义上讲,Realm实质上是一个安全相关的DAO:它封装了数据源的连接细节,并在需要时将相关数据提供给Shiro。当配置Shiro时,你必须至少指定一个Realm,用于认证和(或)授权。配置多个Realm是可以的,但是至少需要一个。
Shiro内置了可以连接大量安全数据源(又名目录)的Realm,如LDAP、关系数据库(JDBC)、类似INI的文本配置资源以及属性文件等。如果系统默认的Realm不能满足需求,你还可以插入代表自定义数据源的自己的Realm实现。
2、实战
1、依赖
<dependency><groupId>com.github.theborakompanioni</groupId><artifactId>thymeleaf-extras-shiro</artifactId><version>2.0.0</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!--Subject 用户SecurityManager 管理所有用户Realm 连接数据--><!--shiro整合spring的包--><!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring --><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.8.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--Thymeleaf 模板--><!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf-spring5 --><dependency><groupId>org.thymeleaf</groupId><artifactId>thymeleaf-spring5</artifactId></dependency><!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-java8time --><dependency><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-java8time</artifactId></dependency><!--连接数据库相关--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!-- 引入 myBatis, 这是MyBatis官方提供的适配 Spring Boot的, 而不是Spring Boot自己的--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.2</version></dependency><!-- https://mvnrepository.com/artifact/com.alibaba/druid --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.10</version></dependency><!--log4j--><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.12</version></dependency>
2、编写Shiro的Config
/*@Qualifier 注解是为了查询Bean的 ,从而使两个方法关联起来*/@Configurationpublic class ShiroConfig {// ShiroFilterFactoryBean: 3@Beanpublic ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();// 设置安全管理器bean.setSecurityManager(defaultWebSecurityManager);// 添加shiro的内置过滤器/*anno: 无需认证就可以访问authc: 必须认证了才能访问user: 必须拥有 记住我 功能才能访问perms: 拥有对某个资源的权限才能访问role: 拥有某个角色权限才能访问*/Map<String, String> filterMap = new LinkedHashMap<>();filterMap.put("/user/add","perms[user:add]");filterMap.put("/user/update","perms[user:update]");filterMap.put("/user/*","authc");bean.setFilterChainDefinitionMap(filterMap);// 设置登录的请求bean.setLoginUrl("/toLogin");// 未授权页面bean.setUnauthorizedUrl("/noauth");return bean;}// DefaultWebSecurityManager: 2@Bean(name = "securityManager")public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();// 关联UserRealmsecurityManager.setRealm(userRealm);return securityManager;}// 创建 Realm 对象 , 需要自定义类: 1@Beanpublic UserRealm userRealm(){return new UserRealm();}// 整合ShiroDialect: 用来整合 shiro thymeleaf@Beanpublic ShiroDialect getShiroDialect(){return new ShiroDialect();}}
// 自定义的 UserRealm extends AuthorizingRealmpublic class UserRealm extends AuthorizingRealm {@AutowiredUserService userService;// 授权@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("执行了=>授权doGetAuthorizationInfo");// SimpleAuthorizationInfoSimpleAuthorizationInfo info = new SimpleAuthorizationInfo();// info.addStringPermission("user:add");// 拿到当前登录的这个对象Subject subject = SecurityUtils.getSubject();User currentUser = (User) subject.getPrincipal(); // 拿到User对象// 设置当前用户的权限info.addStringPermission(currentUser.getPerms());return info;}// 认证@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {System.out.println("执行了=>认证doGetAuthenticationInfo");// 用户名,密码~ 数据中取// String name = "shuai";// String password = "123456";UsernamePasswordToken userToken = (UsernamePasswordToken) token;// 连接真实数据库User user = userService.queryUserByName(userToken.getUsername());if (user==null){ // 没有这个人return null; // 抛出异常 UnknownAccountException}// 把用户放到SessionSubject currentSubject = SecurityUtils.getSubject();Session session = currentSubject.getSession();session.setAttribute("loginUser",user);// 密码认证,shiro内部做了~ , 加密了// user存在subject中return new SimpleAuthenticationInfo(user,user.getPwd(),"");}}
3、编写MyController
@Controllerpublic class MyController {@RequestMapping({"/","index"})public String toIndex(Model model){model.addAttribute("msg","hello shiro");return "index";}@RequestMapping("/user/add")public String add(){return "user/add";}@RequestMapping("/user/update")public String update(){return "user/update";}@RequestMapping("/toLogin")public String toLogin(){return "login";}@RequestMapping("/login")public String login(String username,String password,Model model){// 获取当前的用户对象 SubjectSubject subject = SecurityUtils.getSubject();// 封装用户的登录数据UsernamePasswordToken token = new UsernamePasswordToken(username, password);try {subject.login(token); // 执行登录方法,如果没有异常就说明ok了return "index";}catch (UnknownAccountException e){ // 用户名不存在model.addAttribute("msg","用户名错误");return "login";}catch (IncorrectCredentialsException e){ // 密码不正确model.addAttribute("msg","密码错误");return "login";}}@RequestMapping("/noauth")@ResponseBodypublic String unauthorized(){return "未授权页面";}}
4、整合Mybatis
application.yaml
spring:datasource:username: rootpassword: shuai# 假如时区报错了,就增加一个时区的配置就ok了 serverTimezone=UTCurl: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8driver-class-name: com.mysql.cj.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSource#Spring Boot 默认是不注入这些属性值的,需要自己绑定#druid 数据源专有配置initialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4jfilters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
application.properties
# 应用名称spring.application.name=shiro-springboot# 应用服务 WEB 访问端口server.port=8080# 关闭模板引擎的缓存spring.thymeleaf.cache=false# 整合mybatis# 起别名 Usermybatis.type-aliases-package=com.shuai.pojo# 映射路径mybatis.mapper-locations=classpath:mapper/*.xml
5、测试查询用户
在pojo下编写User实体类
在mapper下编写UserMapper接口
@Mapper@Repositorypublic interface UserMapper {User queryUserByName(String name);}
在resources下创建mapper文件夹下创建UserMapper.xml
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.shuai.mapper.UserMapper"><select id="queryUserByName" parameterType="String" resultType="User">select * from user where name = #{name};</select></mapper>
再编写service文件夹下UserService
public interface UserService {User queryUserByName(String name);}
UserServiceImpl
@Servicepublic class UserServiceImpl implements UserService{@AutowiredUserMapper userMapper;@Overridepublic User queryUserByName(String name) {return userMapper.queryUserByName(name);}}
最后再test中测试,看是否能够查询成功!
@SpringBootTestclass ShiroSpringbootApplicationTests {@AutowiredUserService userService;@Testvoid contextLoads() {System.out.println(userService.queryUserByName("小帅"));}}
6、在index.html中进行权限的测试
命名空间
<!--命名空间的组成就是: thymeleaf的官网地址 + 导入thymeleaf与安全的包-->xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"
<h1>首页</h1><div th:text="${msg}"></div><!--从session中判断值!--><div th:if="${session.loginUser==null}"><a th:href="@{/toLogin}">登录</a></div><hr><div shiro:hasPermission="user:add"><a th:href="@{/user/add}">add</a></div><div shiro:hasPermission="user:update"><a th:href="@{/user/update}">update</a></div>
