文章目录
1、权限的管理
1.1 什么是权限管理
基本上涉及到用户参与的系统都要进行权限管理,权限管理属于系统安全的范畴,权限管理实现对用户访问系统的控制,按照安全规则或者安全策略控制用户可以访问而且只能访问自己被授权的资源。
权限管理包括用户身份认证和授权两部分,简称认证授权。对于需要访问控制的资源用户首先经过身份认证,认证通过后用户具有该资源的访问权限方可访问。
1.2 什么是身份认证
身份认证,就是判断一个用户是否为合法用户的处理过程。最常用的简单身份认证方式是系统通过核对用户输入的用户名和口令,看其是否与系统中存储的该用户的用户名和口令一致,来判断用户身份是否正确。对于采用指纹等系统,则出示指纹;对于硬件Key等刷卡系统,则需要刷卡。
1.3 什么是授权
授权,即访问控制,控制谁能访问哪些资源。主体进行身份认证后需要分配权限方可访问系统的资源,对于某些资源没有权限是无法访问的
2.什么是shiro
Shiro 是一个功能强大且易于使用的Java安全框架,它执行身份验证、授权、加密和会话管理。使用Shiro易于理解的API,您可以快速轻松地保护任何应用程序—从最小的移动应用程序到最大的web和企业应用程序。
Shiro是apache旗下一个开源框架,它将软件系统的安全认证相关的功能抽取出来,实现用户身份认证,权限授权、加密、会话管理等功能,组成了一个通用的安全认证框架。
3.Shiro的核心构架

3.1 Subject
Subject即主体,外部应用与subject进行交互,subject记录了当前操作用户,将用户的概念理解为当前操作的主体,可能是一个通过浏览器请求的用户,也可能是一个运行的程序。
Subject在shiro中是一个接口,接口中定义了很多认证授相关的方法,外部程序通过subject进行认证授,而subject是通过SecurityManager安全管理器进行认证授权
3.2 SecurityManager
SecurityManager即安全管理器,对全部的subject进行安全管理,它是shiro的核心,负责对所有的subject进行安全管理。通过SecurityManager可以完成subject的认证、授权等,实质上SecurityManager是通过Authenticator进行认证,通过Authorizer进行授权,通过SessionManager进行会话管理等。
SecurityManager是一个接口,继承了Authenticator, Authorizer, SessionManager这三个接口。
3.3 Authenticator
Authenticator即认证器,对用户身份进行认证,Authenticator是一个接口,shiro提供ModularRealmAuthenticator实现类,通过ModularRealmAuthenticator基本上可以满足大多数需求,也可以自定义认证器。
3.4 Authorizer
Authorizer即授权器,用户通过认证器认证通过,在访问功能时需要通过授权器判断用户是否有此功能的操作权限。
3.5 Realm
Realm即领域,相当于datasource数据源,securityManager进行安全认证需要通过Realm获取用户权限数据,比如:如果用户身份数据在数据库那么realm就需要从数据库获取用户身份信息。
注意:不要把realm理解成只是从数据源取数据,在realm中还有认证授权校验的相关的代码。
3.6 SessionManager
sessionManager即会话管理,shiro框架定义了一套会话管理,它不依赖web容器的session,所以shiro可以使用在非web应用上,也可以将分布式应用的会话集中在一点管理,此特性可使它实现单点登录。
3.7 SessionDAO
SessionDAO即会话dao,是对session会话操作的一套接口,比如要将session存储到数据库,可以通过jdbc将会话存储到数据库。
3.8 CacheManager
CacheManager即缓存管理,将用户权限数据存储在缓存,这样可以提高性能。
3.9 Cryptography
Cryptography即密码管理,shiro提供了一套加密/解密的组件,方便开发。比如提供常用的散列、加/解密等功能。
4.shiro中的认证
4.1 认证
身份认证,就是判断一个用户是否为合法用户的处理过程。最常用的简单身份认证方式是系统通过核对用户输入的用户名和口令,看其是否与系统中存储的该用户的用户名和口令一致,来判断用户身份是否正确。
4.2 shiro中认证的关键对象
-
Subject:主体
访问系统的用户,主体可以是用户、程序等,进行认证的都称为主体; -
Principal:身份信息
是主体(subject)进行身份认证的标识,标识必须具有唯一性,如用户名、手机号、邮箱地址等,一个主体可以有多个身份,但是必须有一个主身份(Primary Principal)。 -
credential:凭证信息
是只有主体自己知道的安全信息,如密码、证书等。
4.3 认证流程

4.4 认证的开发
1. 创建项目并引入依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.5.1</version>
</dependency>
2. 引入shiro配置文件
配置文件:名称随意,以 .ini 结尾,放在 resources 目录下
注意:在实际的项目开发中并不会使用这种方式,这种方法可以用来初学时练手
[users]
zhangsan=123456
lisi=123456

3.认证实现
public static void main(String[] args) {
//1.创建安全管理器对象
DefaultSecurityManager securityManager = new DefaultSecurityManager();
//2.给安全管理器对象设置realm
securityManager.setRealm(new IniRealm("classpath:shiro.ini"));
//3.SecurityUtils给全局安全工具类设置安全管理器
SecurityUtils.setSecurityManager(securityManager);
//4.关键对象的subject主体
Subject subject = SecurityUtils.getSubject();
//5.创建令牌
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "123456");
try{
System.out.println("认证状态"+subject.isAuthenticated());
subject.login(token);
System.out.println("认证状态"+subject.isAuthenticated());
}
catch (UnknownAccountException e)
{
System.out.println("认证失败,用户名不存在");
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("认证失败");
}
}
4.5. 自定义Realm
通过分析源码可得:
认证:
1.最终执行用户名比较是 在SimpleAccountRealm类 的doGetAuthenticationInfo 方法中完成用户名校验
2.最终密码校验是在 AuthenticatingRealm类 的assertCredentialsMatch方法 中
总结:
AuthenticatingRealm 认证realm doGetAuthenticationInf
AuthorizingRealm 授权realm doGetAuthorizationInfo
自定义Realm的作用:放弃使用.ini文件,使用数据库查询
上边的程序使用的是Shiro自带的IniRealm,IniRealm从ini配置文件中读取用户的信息,大部分情况下需要从系统的数据库中读取用户信息,所以需要自定义realm。
1. 自定义Realm
/**
* 自定义realm实现将认证、授权的来源转化为数据库
*/
public class ConsumerRealm extends AuthorizingRealm{
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//获取token中的用户名
String principal =(String) token.getPrincipal();
System.out.println(principal);
//根据用户名查询数据库的相关信息
if("zhangsan".equals(principal))
{
/**
* 参数一:返回数据库中正确的用户名
* 参数二:返回数据库中正确的密码
* 参数三:提供当前Realm的名字 this.getName
*/
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(principal, "123456", this.getName());
return simpleAuthenticationInfo;
}
return null;
}
}
2. 自定义Realm的测试
/**
* 使用自定义的;Realm
*/
public class TestAuthorizingRealm {
public static void main(String[] args) {
//创建SecurityManager
DefaultSecurityManager securityManager = new DefaultSecurityManager();
//设置自定义Realm
securityManager.setRealm(new ConsumerRealm());
//设置安全工具类
SecurityUtils.setSecurityManager(securityManager);
//通过安全工具类得到Object
Subject subject = SecurityUtils.getSubject();
//创建Token
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "123456");
try
{
subject.login(token);
System.out.println("登录成功");
}
catch (UnknownAccountException e)
{
e.printStackTrace();
System.out.println("用户名不存在");
}
catch (IncorrectCredentialsException e)
{
e.printStackTrace();
System.out.println("密码错误");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
4.6 MD5+Salt+Hash
4.6.1 MD5算法简介
作用:一般用于加密或者签名(校验和)
特点:MD5算法不可逆, 相同的内容无论执行多少次MD5 加密,生成的结果始终一样
生成结果:始终是16进制32位的字符串
MD5基本使用
public class TestMD5Shiro {
public static void main(String[] args) {
//MK5
Md5Hash md5Hash = new Md5Hash("123");
System.out.println(md5Hash.toHex());
//使用MD5+salt处理
Md5Hash md5Hash1 = new Md5Hash("123", "X0*7ps");
System.out.println(md5Hash1.toHex());
//使用md5 + salt + hash散列(参数代表要散列多少次,一般是 1024或2048)
Md5Hash md5Hash2 = new Md5Hash("123", "X0*7ps", 1024);
System.out.println(md5Hash2.toHex());
}
}
4.6.2 自定义是MD5+salt+hash
1. 自定义Realm
public class MD5ConsumerRealm extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//用户名
String principal =(String) token.getPrincipal();
if("zhangsan".equals(principal))
{
/**
* 参数一:返回数据库中正确的用户名
* 参数二:返回数据库中正确的密码
* 参数三:注册时的随机盐
* 参数四:提供当前Realm的名字 this.getName
*/
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
principal,
// "202cb962ac59075b964b07152d234b70",
"8a83592a02263bfe6752b2b5b03a4799",//加盐不散列
//"e4f9bf3e0c58f045e62c23c533fcf633", //加盐散列1024次
ByteSource.Util.bytes("X0*7ps"),
this.getName());
return simpleAuthenticationInfo;
}
return null;
}
}
2. 测试
public class TestMD5ConsumerRealm {
public static void main(String[] args) {
//创建安全管理器
DefaultSecurityManager securityManager = new DefaultSecurityManager();
MD5ConsumerRealm realm = new MD5ConsumerRealm();
//设置realm使用hash凭证匹配器
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName("md5");
//使用的算法散列的次数
// hashedCredentialsMatcher.setHashIterations(1024);
realm.setCredentialsMatcher(hashedCredentialsMatcher);
//设置Realm
securityManager.setRealm(realm);
//将安全管理器注入安全工具
SecurityUtils.setSecurityManager(securityManager);
//认证
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "123");
try {
subject.login(token);
System.out.println("登录成功");
}
catch (UnknownAccountException e)
{
e.printStackTrace();
System.out.println("用户名错误");
}
catch (IncorrectCredentialsException e)
{
e.printStackTrace();
System.out.println("密码错误");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
5.授权
5.1 授权
授权,即访问控制,控制谁能访问哪些资源。主体进行身份认证后需要分配权限方可访问系统的资源,对于某些资源没有权限是无法访问的。
5.2 关键对象
授权可简单理解为who对what(which)进行How操作:
Who,即主体(Subject),主体需要访问系统中的资源。
What,即资源(Resource),如系统菜单、页面、按钮、类方法、系统商品信息等。资源包括资源类型和资源实例,比如商品信息为资源类型,类型为t01的商品为资源实例,编号为001的商品信息也属于资源实例。
How,权限/许可(Permission),规定了主体对资源的操作许可,权限离开资源没有意义,如用户查询权限、用户添加权限、某个类方法的调用权限、编号为001用户的修改权限等,通过权限可知主体对哪些资源都有哪些操作许可。
5.3 授权流程

5.4 授权方式
1. 基于角色的访问控制
RBAC基于角色的访问控制(Role-Based Access Control)是以角色为中心进行访问控制
if(subject.hasRole("admin")){
//操作什么资源
}
2. 基于资源的访问控制
RBAC基于资源的访问控制(Resource-Based Access Control)是以资源为中心进行访问控制
if(subject.isPermission("user:update:01")){ //资源实例
//对资源01用户具有修改的权限
}
if(subject.isPermission("user:update:*")){ //资源类型
//对 所有的资源 用户具有更新的权限
}
5.5 权限字符串
权限字符串的规则是:资源标识符:操作:资源实例标识符,意思是对哪个资源的哪个实例具有什么操作,“:”是资源/操作/实例的分割符,权限字符串也可以使用*通配符。
例子:
用户创建权限:user:create,或user:create:*
用户修改实例001的权限:user:update:001
用户实例001的所有权限:user:*:001
自定义realm
public class MD5ConsumerRealm extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//得到主身份
String primaryPrincipal = (String)principalCollection.getPrimaryPrincipal();
System.out.println("身份信息:"+primaryPrincipal);
//根据身份信息 用户名获取当前用户的角色以及权限信息
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
authorizationInfo.addRole("admin");
authorizationInfo.addRole("user");
//将数据库中查询的权限信息赋值给权限对象
authorizationInfo.addStringPermission("user:*:01");
authorizationInfo.addStringPermission("admin:update:*");
return authorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//用户名
String principal =(String) token.getPrincipal();
if("zhangsan".equals(principal))
{
/**
* 参数一:返回数据库中正确的用户名
* 参数二:返回数据库中正确的密码
* 参数三:注册时的随机盐
* 参数四:提供当前Realm的名字 this.getName
*/
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
principal,
// "202cb962ac59075b964b07152d234b70",
"8a83592a02263bfe6752b2b5b03a4799",//加盐不散列
//"e4f9bf3e0c58f045e62c23c533fcf633", //加盐散列1024次
ByteSource.Util.bytes("X0*7ps"),
this.getName());
return simpleAuthenticationInfo;
}
return null;
}
}
测试
public class TestMD5ConsumerRealm {
public static void main(String[] args) {
//创建安全管理器
DefaultSecurityManager securityManager = new DefaultSecurityManager();
MD5ConsumerRealm realm = new MD5ConsumerRealm();
//设置realm使用hash凭证匹配器
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName("md5");
//使用的算法散列的次数
// hashedCredentialsMatcher.setHashIterations(1024);
realm.setCredentialsMatcher(hashedCredentialsMatcher);
//设置Realm
securityManager.setRealm(realm);
//将安全管理器注入安全工具
SecurityUtils.setSecurityManager(securityManager);
//认证
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "123");
try {
subject.login(token);
System.out.println("登录成功");
}
catch (UnknownAccountException e)
{
e.printStackTrace();
System.out.println("用户名错误");
}
catch (IncorrectCredentialsException e)
{
e.printStackTrace();
System.out.println("密码错误");
}
catch (Exception e)
{
e.printStackTrace();
}
//认证用户进行授权
if(subject.isAuthenticated())
{
//1.基于角色权限控制
System.out.println("具有单个角色权限");
System.out.println(subject.hasRole("admin"));
//基于多个角色的是否具有其中一个权限控制
boolean[] hasRoles = subject.hasRoles(Arrays.asList("admin", "users"));
System.out.println("具有多个角色权限");
for(boolean b:hasRoles)
{
System.out.println(b);
}
//基于多角色控制
boolean hasAllRoles = subject.hasAllRoles(Arrays.asList("admin", "user"));
System.out.println("同时具备多个角色权限");
System.out.println(hasAllRoles);
System.out.println("====================");
System.out.println("具备单个访问权限");
System.out.println("权限:"+subject.isPermitted("user:*:01"));
System.out.println("权限"+subject.isPermitted("admin:update:01"));
//分别具有哪些权限
boolean[] booleans = subject.isPermitted("user:*:01", "admin:update:01");
System.out.println("具备多个访问权限");
for(boolean b:booleans )
{
System.out.println(b);
}
//同时具备多个访问权限
boolean permittedAll = subject.isPermittedAll("user:*:01", "admin:update:01");
System.out.println("同时具有多个访问权限");
System.out.println(permittedAll);
}
}
}
6. 整合springboot项目
6.1 整合思路

6.2 构建项目

6.2.1 引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 引入jsp解析的依赖-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-starter</artifactId>
<version>1.5.1</version>
</dependency>
</dependencies>
6.2.2 yml
spring:
mvc:
view:
suffix: .jsp
prefix: /
server:
port: 8081
servlet:
context-path: /
jsp:
init-parameters: true
6.2.3 建立相关的页面
在main目录下创建一个webapp目录,webapp目录下创建一个index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>系统主页</h1>
<ul>
<li ><a href="./login.jsp">用户管理</a> </li>
<li><a href="#">商品管理</a> </li>
<li><a href="#">订单管理</a> </li>
<li><a href="#">物理管理</a> </li>
</ul>
</body>
</html>
在main目录下创建一个webapp目录,webapp目录下创建一个login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
用户登录
</body>
</html>
6.2.4 创建shiro相关的配置类
ShiroConfig
/**
* 整合shiro框架相关对配置类
*/
@Configuration
public class ShiroConfig {
// 创建shiroFilter 负责拦截所有请求
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager)
{
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//给Filter设置安全管理器
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
//配置系统受限资源
//配置系统公共资源
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("/index.jsp","authc");//authc 请求这个资源需要认证和授权
// 默认认证界面路径
shiroFilterFactoryBean.setLoginUrl("/login.jsp");
shiroFilterFactoryBean.setFilterChainDefinitionMap(hashMap);
return shiroFilterFactoryBean;
}
//创建安全管理器
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm)
{
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
//给安全管理器设置Realm
defaultWebSecurityManager.setRealm(realm);
return defaultWebSecurityManager;
}
//创建自定义Realm
@Bean
public Realm getRealm()
{
CustomerRealm customerRealm = new CustomerRealm();
return customerRealm;
}
}
创建Realm相关对配置类
//自定义Realm
public class CustomerRealm extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
return null;
}
}
6.3 shiro常见的过滤器
注意: shiro提供和多个默认的过滤器,我们可以用这些过滤器来配置控制指定url的权限:
| 配置缩写 | 对应的过滤器 | 功能 |
|---|---|---|
| anon | AnonymousFilter | 指定url可以匿名访问(访问时不需要认证授权)可以认为是公共资源 |
| authc | FormAuthenticationFilter | 指定url需要form表单登录,默认会从请求中获取username、password,rememberMe等参数并尝试登录,如果登录不了就会跳转到loginUrl配置的路径。我们也可以用这个过滤器做默认的登录逻辑,但是一般都是我们自己在控制器写登录逻辑的,自己写的话出错返回的信息都可以定制嘛。 |
| authcBasic | BasicHttpAuthenticationFilter | 指定url需要basic登录 |
| logout | LogoutFilter | 登出过滤器,配置指定url就可以实现退出功能,非常方便 |
| noSessionCreation | NoSessionCreationFilter | 禁止创建会话 |
| perms | PermissionsAuthorizationFilter | 需要指定权限才能访问 |
| port | PortFilter | 需要指定端口才能访问 |
| rest | HttpMethodPermissionFilter | 将http请求方法转化成相应的动词来构造一个权限字符串,这个感觉意义不大,有兴趣自己看源码的注释 |
| roles | RolesAuthorizationFilter | 需要指定角色才能访问 |
| ssl | SslFilter | 需要https请求才能访问 |
| user | UserFilter | 需要已登录或“记住我”的用户才能访问 |
6.4 认证和退出对实现
1. 登录页面的实现
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>用户登录</h1>
<form action="${pageContext.request.contextPath}/user/login" method="post">
用户名:<input type="text" name="username">
<br>
密码:<input type="password" name="password">
<br>
<input type="submit" value="登录">
</form>
</body>
</html>
2. 这index.jsp中添加退出的链接
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>系统主页</h1>
<a href="${pageContext.request.contextPath}/user/logout">退出</a>
<ul>
<li ><a href="./login.jsp">用户管理</a> </li>
<li><a href="#">商品管理</a> </li>
<li><a href="#">订单管理</a> </li>
<li><a href="#">物理管理</a> </li>
</ul>
</body>
</html>
3. 编写ealm
//自定义Realm
public class CustomerRealm extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("=============");
Object principal =(String) token.getPrincipal();
if("admin".equals(principal))
{
return new SimpleAuthenticationInfo(principal,"123456",this.getName());
}
// new SimpleAuthenticationInfo()
return null;
}
}
4. 相关的配置类
先配置公共资源在配置需要认证授权的资源
@Configuration
public class ShiroConfig {
// 创建shiroFilter 负责拦截所有请求
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager)
{
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//给Filter设置安全管理器
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
//配置系统受限资源
//配置系统公共资源
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("/user/login","anon");//anon设置为公共资源
hashMap.put("/**","authc");//authc 请求这个资源需要认证和授权 **所以资源需要认证
// 默认认证界面路径
shiroFilterFactoryBean.setLoginUrl("/login.jsp");
shiroFilterFactoryBean.setFilterChainDefinitionMap(hashMap);
return shiroFilterFactoryBean;
}
//创建安全管理器
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm)
{
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
//给安全管理器设置Realm
defaultWebSecurityManager.setRealm(realm);
return defaultWebSecurityManager;
}
//创建自定义Realm
@Bean
public Realm getRealm()
{
CustomerRealm customerRealm = new CustomerRealm();
return customerRealm;
}
}
5. 编写登录退出的controller
@Controller
@RequestMapping("user")
public class UserController {
/**
* 退出登录
* @return
*/
@RequestMapping("/logout")
public String logout()
{
Subject subject = SecurityUtils.getSubject();
subject.logout();//退出用户
return "redirect:/login.jsp";
}
/**
* 用了处理身份认证
* @param username
* @param password
* @return
*/
@RequestMapping("login")
public String login(String username,String password)
{
//获取主体对象
Subject subject = SecurityUtils.getSubject();
try{
subject.login(new UsernamePasswordToken(username,password));
return "redirect:/index.jsp";
}
catch (UnknownAccountException e)
{
e.printStackTrace();
System.out.println("用户名不存在");
}
catch (IncorrectCredentialsException e)
{
e.printStackTrace();
System.out.println("密码错误");
}
return "redirect:/login.jsp";
}
}
6.5 MD5+salt认证实现
6.5.1用户注册
1. 添加数据库,并建立表

2.添加依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.19</version>
</dependency>
3.数据库的相关配置

4.加密工具类的编写
SaltUtils
public class SaltUtils {
public static String getSalt(int n)
{
char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*".toCharArray();
StringBuffer sb = new StringBuffer();
for(int i=0;i<n;i++)
{
char c = chars[new Random().nextInt(chars.length)];
sb.append(c);
}
return sb.toString();
}
}
5. 实体类的编写
User
public class User {
private int id;
private String username;
private String password;
private String salt;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", salt='" + salt + '\'' +
'}';
}
public User() {
}
public User(int id, String username, String password, String salt) {
this.id = id;
this.username = username;
this.password = password;
this.salt = salt;
}
}
6.用户注册接口的编写
在UserController中
/**
* 用户注册
* @param user
* @return
*/
@RequestMapping("/register")
public String register(User user)
{
try{
System.out.println(user);
userService.register(user);
return "redirect:/index.jsp";
}
catch (Exception e)
{
e.printStackTrace();
return "redirect:/register.jsp";
}
}
7.service层的编写
UserService
public interface UserService {
/**
* 用户注册
* @param user
*/
public void register(User user);
}
UserServiceImpl
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public void register(User user) {
//生成随机盐
String salt = SaltUtils.getSalt(8);
//将随机盐存入对象
user.setSalt(salt);
//调用MD5+salt+hash散列对明文进行加密
Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);
user.setPassword(md5Hash.toHex());
userMapper.save(user);
}
}
8.Mapper层的编写
UserMapper
@Mapper
@Repository
public interface UserMapper {
void save(User user);
}
这同级目录下创建UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.blb.shiro.mapper.UserMapper">
<insert id="save" parameterType="User" useGeneratedKeys="true" keyProperty="id">
insert into user values (#{id},#{username},#{password},#{salt})
</insert>
</mapper>
6.5.2
1. 修改自定义Realm的校验匹配器
//创建自定义Realm
@Bean
public Realm getRealm()
{
CustomerRealm customerRealm = new CustomerRealm();
//修改凭证校验匹配器
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
//设置加密算法为MDK加密
credentialsMatcher.setHashAlgorithmName("MD5");
//设置散列次数
credentialsMatcher.setHashIterations(1024);
customerRealm.setCredentialsMatcher(credentialsMatcher);
return customerRealm;
}
2. 在UserMapper中写通过用户名查找用户信息,后台进行校验
User findByUserName(String username);
<select id="findByUserName" parameterType="String" resultType="User">
select id,username,password,salt from user where username=#{username}
</select>
3.在UserService中写根据用户名查找用户信息的服务
UserService中
/**
* 通过用户名查找用户
* @param username
* @return
*/
public User findUserByName(String username);
UserServiceImpl中
@Override
public User findUserByName(String username) {
return userMapper.findByUserName(username);
}
4.在自定义的Real中修改验证的方法
public class CustomerRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("=============");
//得到身份信息
Object principal =(String) token.getPrincipal();
User user = userService.findUserByName((String) principal);
if(!ObjectUtils.isEmpty(user))
{
return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
}
// new SimpleAuthenticationInfo()
return null;
}
}
6.6授权的实现
6.6.1 没有数据库
1.页面资源的实现
- 在自定义realm中加上角色和资源权限的添加
CustomerRealm
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
Object primaryPrincipal = (String)principalCollection.getPrimaryPrincipal();
System.out.println("调用权限认证"+primaryPrincipal);
if("a".equals(primaryPrincipal))
{
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
authorizationInfo.addRole("user");
authorizationInfo.addStringPermission("user:*:*");
return authorizationInfo;
}
return null;
}
2. 在index.jsp中加上权限控制的标签
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>系统主页</h1>
<a href="${pageContext.request.contextPath}/user/logout">退出</a>
<ul>
<shiro:hasAnyRoles name="user,admin"> <!--有user和admin权限即可访问 -->
<li ><a href="./login.jsp">用户管理</a>
<ul>
<shiro:hasPermission name="user:add:*"> <!--基于权限字符串的控制-->
<li><a href="#">添加</a> </li>
</shiro:hasPermission>
<shiro:hasPermission name="user:delete:*">
<li><a href="#">删除</a> </li>
</shiro:hasPermission>
<shiro:hasPermission name="user:update:*">
<li><a href="#">修改</a> </li>
</shiro:hasPermission>
<shiro:hasPermission name="user:find:*">
<li><a href="#">查询</a> </li>
</shiro:hasPermission>
</ul>
</li>
</shiro:hasAnyRoles>
<shiro:hasRole name="admin">
<li><a href="#">商品管理</a> </li>
<li><a href="#">订单管理</a> </li>
<li><a href="#">物理管理</a> </li>
</shiro:hasRole>
</ul>
</body>
</html>
2.代码方式授权
新建一个OrderController
@Controller
@RequestMapping("order")
public class OrderController {
@RequestMapping("save")
public String save()
{
System.out.println("save");
//获取主体对象
Subject subject = SecurityUtils.getSubject();
//基于角色
if(subject.hasRole("order"))
{
System.out.println("生成订单完成");
}
else
{
System.out.println("暂时没有权限访问");
}
if(subject.isPermitted("user:*:*")) //基于权限字符串
{
System.out.println("有该资源权限");
}
else
{
System.out.println("对不起您没有该资源权限");
}
return "redirect:/index.jsp";
}
}
3.方法调用授权
@RequiresRoles 用来基于角色进行授权
@RequiresPermissions 用来基于权限进行授权
@RequestMapping("/update")
@RequiresRoles(value = {"admin","user"})//同时具有admin和user权限才可访问
@RequiresPermissions(value = {"user:update:01","user:update:02"}) //用来判断权限字符串 如果有多个同时具有才可以
public String update()
{
System.out.println("update");
return "redirect:/index.jsp";
}
6.7连接数据库

6.7.1创建对应的表
CREATE TABLE `role` (
`id` int(6) NOT NULL AUTO_INCREMENT,
`name` varchar(60) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `role` (`id`, `name`)
VALUES
(1, 'admin') ,
(2,"user"),
(3,"product");
CREATE TABLE `user` (
`id` int(6) NOT NULL AUTO_INCREMENT,
`username` varchar(40) DEFAULT NULL,
`password` varchar(40) DEFAULT NULL,
`salt` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
CREATE TABLE `pers` (
`id` int(6) NOT NULL AUTO_INCREMENT,
`name` varchar(60) DEFAULT NULL,
`url` varbinary(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `student6`.`pers` (`id`, `name`, `url`)
VALUES
(1, 'user:*:*', ''),
(2,'product:*:01','') ;
CREATE TABLE `user_role` (
`id` int(6) NOT NULL AUTO_INCREMENT,
`user_id` int(6) DEFAULT NULL,
`role_id` int(6) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `student6`.`user_role` (`id`, `user_id`, `role_id`)
VALUES
(1,1,1),
(2,2,2),
(3,2,3) ;
CREATE TABLE `role_pers` (
`id` int(6) NOT NULL AUTO_INCREMENT,
`role_id` int(6) DEFAULT NULL,
`pers_id` int(6) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `role_pers` (`id`, `role_id`, `pers_id`)
VALUES
(1, 1, 1),
(2, 1, 2),
(3, 2, 1),
(4, 3, 2) ;
6.7.2实体类
User
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String username;
private String password;
private String salt;
//定义角色集合
private List<Role> roles;
}
Role
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Role {
private int id;
private String name;
//定义权限的集合
private List<Pers>pers;
}
Pers
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Pers {
private int id;
private String name;
private String urL;
}
6.7.3Mapper层
xml配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.blb.shiro.mapper.UserMapper">
<insert id="save" parameterType="User" useGeneratedKeys="true" keyProperty="id">
insert into user1 values (#{id},#{username},#{password},#{salt})
</insert>
<select id="findByUserName" parameterType="String" resultType="User">
select id,username,password,salt from user1 where username=#{username}
</select>
<resultMap id="userMap" type="User">
<id column="uid" property="id"/>
<result column="username" property="username"/>
<!--角色信息-->
<collection property="roles" javaType="list" ofType="Role">
<id column="id" property="id"/>
<result column="rname" property="name"/>
</collection>
</resultMap>
<select id="findRoleByUserName" resultMap="userMap" parameterType="String">
SELECT u.id uid,u.username,r.id,r.name rname
FROM user1 u
LEFT JOIN user_role ur
ON u.id=ur.user_id
LEFT JOIN role r
ON ur.role_id=r.id
WHERE u.username=#{username}
</select>
<select id="findPersByRoleId" parameterType="Integer" resultType="Pers">
SELECT p.id,p.name,p.url,a.name
FROM role a
LEFT JOIN role_pers b
ON a.id=b.role_id
LEFT JOIN pers p
ON b.pers_id=p.id
WHERE a.id=#{id}
</select>
</mapper>
UserMapper
@Mapper
@Repository
public interface UserMapper {
void save(User user);
User findByUserName(String username);
//根据用户名称查找用户角色
User findRoleByUserName(String username);
//根据角色id查找权限集合
List<Pers> findPersByRoleId(int id);
}
2.7.4 Service层
UserService
public interface UserService {
/**
* 用户注册
* @param user
*/
public void register(User user);
/**
* 通过用户名查找用户
* @param username
* @return
*/
public User findUserByName(String username);
/**
* 根据用户名称查找用户角色
* @param username
* @return
*/
User findRoleByUserName(String username);
/**
* 根据角色id查找权限集合
* @param id
* @return
*/
List<Pers> findPersByRoleId(int id);
}
impl
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public void register(User user) {
//生成随机盐
String salt = SaltUtils.getSalt(8);
//将随机盐存入对象
user.setSalt(salt);
//调用MD5+salt+hash散列对明文进行加密
Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);
user.setPassword(md5Hash.toHex());
userMapper.save(user);
}
@Override
public User findUserByName(String username) {
return userMapper.findByUserName(username);
}
@Override
public User findRoleByUserName(String username) {
return userMapper.findRoleByUserName(username);
}
@Override
public List<Pers> findPersByRoleId(int id) {
return userMapper.findPersByRoleId(id);
}
}
2.7.5 自定义Realm的授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String primaryPrincipal = (String)principalCollection.getPrimaryPrincipal();
// System.out.println("调用权限认证"+primaryPrincipal);
//通过用户名获取角色信息
User user = userService.findRoleByUserName(primaryPrincipal);
List<Role> roleList = user.getRoles();
System.out.println(roleList);
if(roleList.size()!=0)
{
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
for(Role role:roleList)
{
authorizationInfo.addRole(role.getName());
//权限信息
List<Pers> persList = userService.findPersByRoleId(role.getId());
System.out.println(persList);
if(persList.size()!=0)
{
for(Pers pers:persList)
{
authorizationInfo.addStringPermission(pers.getName());
}
}
}
return authorizationInfo;
}
return null;
}
6.8使用CacheManager
6.8.1 Cache的作用
- cache缓存:计算机内存中的一段数据
- 作用:用来减轻DB的访问压力,从而提高系统的查询效率
- 流程

6.8.2使用shiro中默认EhCache实现缓存
1. 引入依赖
<!--引入shiro和ehcache-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.5.1</version>
</dependency>
2. 在自定义Realm中开启缓存
ShiroConfig中
//创建自定义Realm
@Bean
public Realm getRealm()
{
CustomerRealm customerRealm = new CustomerRealm();
//修改凭证校验匹配器
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
//设置加密算法为MDK加密
credentialsMatcher.setHashAlgorithmName("MD5");
//设置散列次数
credentialsMatcher.setHashIterations(1024);
customerRealm.setCredentialsMatcher(credentialsMatcher);
//开启缓存管理
customerRealm.setCacheManager(new EhCacheManager());
//开启全局缓存
customerRealm.setCachingEnabled(true);
//开启认证缓存
customerRealm.setAuthenticationCachingEnabled(true);
customerRealm.setAuthenticationCacheName("AuthenticationCache");
//开启授权缓存
customerRealm.setAuthorizationCachingEnabled(true);
customerRealm.setAuthorizationCacheName("AuthorizationCache");
return customerRealm;
}
6.9shiro中使用redis作为缓存
1. 添加redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. yml中配置redis的连接
spring:
redis:
port: 6379
host: localhost
database: 0
3. 启动redis服务
4.开发RedisCacheManager
自定义shiro缓存管理器
/**
* 自定义shiro缓存管理器
*/
//自定义redis实现
public class RedisCache<K,V> implements Cache<K,V> {
private String cacheName;
public RedisCache() {
}
public RedisCache(String cacheName) {
this.cacheName = cacheName;
}
@Override
public V get(K k) throws CacheException {
System.out.println("get key:"+k);
RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
Object o = redisTemplate.opsForValue().get(k.toString());
// Object o = redisTemplate.opsForHash().get(this.cacheName, k.toString());
return (V)o;
}
@Override
public V put(K k, V v) throws CacheException {
System.out.println("put key:"+k);
System.out.println("put value:"+v);
RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.opsForValue().set(k.toString(),v);
// redisTemplate.opsForHash().put(this.cacheName,k.toString(),v);
return null;
}
@Override
public V remove(K k) throws CacheException {
RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
return (V) redisTemplate.opsForHash().delete(this.cacheName,k.toString());
}
@Override
public void clear() throws CacheException {
RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
redisTemplate.delete(this.cacheName);
}
@Override
public int size() {
RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
return redisTemplate.opsForHash().size(this.cacheName).intValue();
}
@Override
public Set<K> keys() {
RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
return redisTemplate.opsForHash().keys(this.cacheName);
}
@Override
public Collection<V> values() {
RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
return redisTemplate.opsForHash().values(this.cacheName);
}
}
6.启动项目测试发现报错

错误解释: 由于shiro中提供的simpleByteSource实现没有实现序列化,所有在认证时出现错误信息
解决方案: 需要自动salt实现序列化
自定义salt实现序列化接口
public class MyByteSource implements ByteSource, Serializable {
private byte[] bytes;
private String cachedHex;
private String cachedBase64;
public MyByteSource(){
}
public MyByteSource(byte[] bytes) {
this.bytes = bytes;
}
public MyByteSource(char[] chars) {
this.bytes = CodecSupport.toBytes(chars);
}
public MyByteSource(String string) {
this.bytes = CodecSupport.toBytes(string);
}
public MyByteSource(ByteSource source) {
this.bytes = source.getBytes();
}
public MyByteSource(File file) {
this.bytes = (new BytesHelper()).getBytes(file);
}
public MyByteSource(InputStream stream) {
this.bytes = (new BytesHelper()).getBytes(stream) ;
}
public static boolean isCompatible(Object o) {
return o instanceof byte[] || o instanceof char[] || o instanceof String || o instanceof ByteSource || o instanceof File || o instanceof InputStream;
}
public byte[] getBytes() {
return this.bytes;
}
public boolean isEmpty() {
return this.bytes == null || this.bytes.length == 0;
}
public String toHex() {
if (this.cachedHex == null) {
this.cachedHex = Hex.encodeToString(this.getBytes());
}
return this.cachedHex;
}
public String toBase64() {
if (this.cachedBase64 == null) {
this.cachedBase64 = Base64.encodeToString(this.getBytes());
}
return this.cachedBase64;
}
public String toString() {
return this.toBase64();
}
public int hashCode() {
return this.bytes != null && this.bytes.length != 0 ? Arrays.hashCode(this.bytes) : 0;
}
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (o instanceof ByteSource) {
ByteSource bs = (ByteSource)o;
return Arrays.equals(this.getBytes(), bs.getBytes());
} else {
return false;
}
}
class BytesHelper extends CodecSupport {
private BytesHelper() {
}
public byte[] getBytes(File file) {
return this.toBytes(file);
}
public byte[] getBytes(InputStream stream) {
return this.toBytes(stream);
}
}
}
在自定义Realm中使用自定义salt

6.10 页面生成验证码
1. 生成验证码的工具类
```package com.blb.shiro.utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;
public class VerifyCodeUtils{
//使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
private static Random random = new Random();
/**
* 使用系统默认字符源生成验证码
* @param verifySize 验证码长度
* @return
*/
public static String generateVerifyCode(int verifySize){
return generateVerifyCode(verifySize, VERIFY_CODES);
}
/**
* 使用指定源生成验证码
* @param verifySize 验证码长度
* @param sources 验证码字符源
* @return
*/
public static String generateVerifyCode(int verifySize, String sources){
if(sources == null || sources.length() == 0){
sources = VERIFY_CODES;
}
int codesLen = sources.length();
Random rand = new Random(System.currentTimeMillis());
StringBuilder verifyCode = new StringBuilder(verifySize);
for(int i = 0; i < verifySize; i++){
verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
}
return verifyCode.toString();
}
/**
* 生成随机验证码文件,并返回验证码值
* @param w
* @param h
* @param outputFile
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, outputFile, verifyCode);
return verifyCode;
}
/**
* 输出随机验证码图片流,并返回验证码值
* @param w
* @param h
* @param os
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, os, verifyCode);
return verifyCode;
}
/**
* 生成指定验证码图像文件
* @param w
* @param h
* @param outputFile
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
if(outputFile == null){
return;
}
File dir = outputFile.getParentFile();
if(!dir.exists()){
dir.mkdirs();
}
try{
outputFile.createNewFile();
FileOutputStream fos = new FileOutputStream(outputFile);
outputImage(w, h, fos, code);
fos.close();
} catch(IOException e){
throw e;
}
}
/**
* 输出指定验证码图片流
* @param w
* @param h
* @param os
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
int verifySize = code.length();
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Random rand = new Random();
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
Color[] colors = new Color[5];
Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
Color.PINK, Color.YELLOW };
float[] fractions = new float[colors.length];
for(int i = 0; i < colors.length; i++){
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
fractions[i] = rand.nextFloat();
}
Arrays.sort(fractions);
g2.setColor(Color.GRAY);// 设置边框色
g2.fillRect(0, 0, w, h);
Color c = getRandColor(200, 250);
g2.setColor(c);// 设置背景色
g2.fillRect(0, 2, w, h-4);
//绘制干扰线
Random random = new Random();
g2.setColor(getRandColor(160, 200));// 设置线条的颜色
for (int i = 0; i < 20; i++) {
int x = random.nextInt(w - 1);
int y = random.nextInt(h - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
}
// 添加噪点
float yawpRate = 0.05f;// 噪声率
int area = (int) (yawpRate * w * h);
for (int i = 0; i < area; i++) {
int x = random.nextInt(w);
int y = random.nextInt(h);
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
}
shear(g2, w, h, c);// 使图片扭曲
g2.setColor(getRandColor(100, 160));
int fontSize = h-4;
Font font = new Font("Algerian", Font.ITALIC, fontSize);
g2.setFont(font);
char[] chars = code.toCharArray();
for(int i = 0; i < verifySize; i++){
AffineTransform affine = new AffineTransform();
affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
g2.setTransform(affine);
g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
}
g2.dispose();
ImageIO.write(image, "jpg", os);
}
private static Color getRandColor(int fc, int bc) {
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
}
return color;
}
private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
}
private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private static void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
}
private static void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10; // 50;
boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
}
public static void main(String[] args) throws IOException {
//获取验证码
String s = generateVerifyCode(4);
//将验证码放入图片中
outputImage(260,60,new File("/Users/chenyannan/Desktop/安工资料/aa.jpg"),s);
System.out.println(s);
}
}
2. 开发控制器
/**
* 验证码方法
*/
@RequestMapping("getImage")
public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
//生成验证码
String code = VerifyCodeUtils.generateVerifyCode(4);
//验证码放入session
session.setAttribute("code",code);
//验证码存入图片
ServletOutputStream outputStream = response.getOutputStream();
response.setContentType("image/png");
VerifyCodeUtils.outputImage(200,60,outputStream,code);
}
3. 放行验证码

4.登录页面修改
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>用户登录</h1>
<form action="${pageContext.request.contextPath}/user/login" method="post">
用户名:<input type="text" name="username">
<br>
密码:<input type="password" name="password">
<br>
输入验证码:<input type="text" name="code"><img src="${pageContext.request.contextPath}/user/getImage" alt="">
<br>
<input type="submit" value="登录">
<a href="register.jsp">注册</a>
</form>
</body>
</html>
5. 登录接口的改写
/**
* 用于处理身份认证
* @return
*/
@RequestMapping("login")
public String login(String username,String password,String code,HttpSession session)
{
//比较验证码
String codes =(String) session.getAttribute("code");
try {
if(code.equals(codes))
{
//获取主体对象
Subject subject = SecurityUtils.getSubject();
subject.login(new UsernamePasswordToken(username,password));
return "redirect:/index.jsp";
}
else
{
throw new RuntimeException("验证码错误");
}
}
catch (UnknownAccountException e)
{
e.printStackTrace();
System.out.println("用户名不存在");
}
catch (IncorrectCredentialsException e)
{
e.printStackTrace();
System.out.println("密码错误");
}
catch (Exception e)
{
e.printStackTrace();
}
return "redirect:/login.jsp";
}
6.10 整合Thymeleaf页面
1. 添加依赖
<!--shiro-thymeleaf -->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-starter</artifactId>
<version>1.5.1</version>
</dependency>
2.页面中引入命名空间
<html xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
3.常见权限控制标签使用
<!-- 验证当前用户是否为“访客”,即未认证(包含未记住)的用户。 -->
<p shiro:guest="">Please <a href="login.html">login</a></p>
<!-- 认证通过或已记住的用户。 -->
<p shiro:user="">
Welcome back John! Not John? Click <a href="login.html">here</a> to login.
</p>
<!-- 已认证通过的用户。不包含已记住的用户,这是与user标签的区别所在。 -->
<p shiro:authenticated="">
Hello, <span shiro:principal=""></span>, how are you today?
</p>
<a shiro:authenticated="" href="updateAccount.html">Update your contact information</a>
<!-- 输出当前用户信息,通常为登录帐号信息。 -->
<p>Hello, <shiro:principal/>, how are you today?</p>
<!-- 未认证通过用户,与authenticated标签相对应。与guest标签的区别是,该标签包含已记住用户。 -->
<p shiro:notAuthenticated="">
Please <a href="login.html">login</a> in order to update your credit card information.
</p>
<!-- 验证当前用户是否属于该角色。 -->
<a shiro:hasRole="admin" href="admin.html">Administer the system</a><!-- 拥有该角色 -->
<!-- 与hasRole标签逻辑相反,当用户不属于该角色时验证通过。 -->
<p shiro:lacksRole="developer"><!-- 没有该角色 -->
Sorry, you are not allowed to developer the system.
</p>
<!-- 验证当前用户是否属于以下所有角色。 -->
<p shiro:hasAllRoles="developer, 2"><!-- 角色与判断 -->
You are a developer and a admin.
</p>
<!-- 验证当前用户是否属于以下任意一个角色。 -->
<p shiro:hasAnyRoles="admin, vip, developer,1"><!-- 角色或判断 -->
You are a admin, vip, or developer.
</p>
<!--验证当前用户是否拥有指定权限。 -->
<a shiro:hasPermission="userInfo:add" href="createUser.html">添加用户</a><!-- 拥有权限 -->
<!-- 与hasPermission标签逻辑相反,当前用户没有制定权限时,验证通过。 -->
<p shiro:lacksPermission="userInfo:del"><!-- 没有权限 -->
Sorry, you are not allowed to delete user accounts.
</p>
<!-- 验证当前用户是否拥有以下所有角色。 -->
<p shiro:hasAllPermissions="userInfo:view, userInfo:add"><!-- 权限与判断 -->
You can see or add users.
</p>
<!-- 验证当前用户是否拥有以下任意一个权限。 -->
<p shiro:hasAnyPermissions="userInfo:view, userInfo:del"><!-- 权限或判断 -->
You can see or delete users.
</p>
<a shiro:hasPermission="pp" href="createUser.html">Create a new User</a>
4.加入shiro的方言配置
页面标签不起作用一定要记住加入方言处理
在shiroConfig中
@Bean(name = "shiroDialect")
public ShiroDialect shiroDialect()
{
return new ShiroDialect();
}
1803

被折叠的 条评论
为什么被折叠?



