初始shiro
文章目录
- 初始shiro
- 一、shiro是什么?
- 二、ShiroConfig配置
- 三、测试代码案例
- 四、自定义认证器进行多Realm认证
- 五、统一返回处理
- 六、统一异常处理
- 七、常见问题处理
- 7.1 org.crazycake.shiro.exception.SerializationException: serialize error, object=
- 7.2 No SecurityManager accessible to the calling code
- 7.3 rememberMe时,Userinfo必须实现序列化接口
- 7.4 xxxx is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)解决
- 7.5 事务失效的解决方法
一、shiro是什么?
1.shiro简介
官网地址:shiro官网
Apache Shiro是一个强大且易用的Java安全框架,用来进行身份验证、授权、密码和会话管理。使用Shiro的易于理解API,你可以快速、轻松地获取任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序
2.结构分析
shiro架构图:官网架构图
(1)从外部整体看shiro框架
即从应用程序角度来看,shiro是如何来进行工作的。
api | 说明 |
---|---|
Subject | 主体,应用代码直接交互的对象是 Subject,也就是说 Shiro 的对外 API 核心就是 Subject , 代表了当前“用户”,这个用户不一定是一个具体的人,与当前应用交互的任何东西都是Subject,如网络爬虫,机器人等;即一个抽象概念;所有Subject都绑定到SecurityManager,与Subject的所有交互都会委托给SecurityManager;可以把Subject认为是一个门面;SecurityManager才是实际的执行者; |
ShiroSecurityManager | 安全管理器,即所有与安全有关的操作都会与SecurityManager交互且它管理着所有Subject;可以看出它是Shiro的核心,它负责与后面介绍的其它组件进行交互,可以把它看成DispathcherServlet前端控制器 |
Realm | 域,Shiro从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法;也需要从Realm得到用户相应的角色/权限进行验证用户是否能进行操作;可以把Realm看成DataSource,即安全数据源 |
也就是说最简单的一个Shiro应用:
1、应用代码通过Subject来进行认证和授权,而Subject又委托给SecurityManager;
2、我们需要给Shiro的SecurityManager注入Realm,从而让SecurityManager能得到合法的用户及其权限进行判断。
从以上也可以看出,Shiro不提供维护用户/权限,而是通过Realm让开发人员自己注入。
(2)从外部整体看shiro框架
组件 | 说明 |
---|---|
Subject | 主体,主体可以是任何可以与应用交互的“用户” |
SecurityManager | 相当于SpringMVC中的DispatcherServlet或者Struts2中的FilterDispatcher;是Shiro的心脏;所有具体的交互都通过SecurityManager进行控制;它管理着所有Subject、且负责进行认证和授权、及会话、缓存的管理 |
Authenticator | 认证器,负责主体认证的,这是一个扩展点,如果用户觉得Shiro默认的不好,可以自定义实现;其需要认证策略(Authentication Strategy),即什么情况下算用户认证通过了 |
Authrizer | 授权器或者访问控制器,用来决定主体是否有权限进行相应的操作;即控制着用户能访问应用中的哪些功能 |
Realm | 可以有1个或多个Realm,可以认为是安全实体数据源,即用于获取安全实体的;可以是JDBC实现,也可以是LDAP实现,或者内存实现等等;由用户提供;注意:Shiro不知道你的用户/权限存储在哪及以何种格式存储;所以我们一般在应用中都需要实现自己的Realm; |
SessionManager | 如果写过Servlet就应该知道Session的概念,Session呢需要有人去管理它的生命周期,这个组件就是SessionManager;而Shiro并不仅仅可以用在Web环境,也可以用在如普通的JavaSE环境、EJB等环境;所有呢,Shiro就抽象了一个自己的Session来管理主体与应用之间交互的数据;这样的话,比如我们在Web环境用,刚开始是一台Web服务器;接着又上了台EJB服务器;这时想把两台服务器的会话数据放到一个地方,这个时候就可以实现自己的分布式会话(如把数据放到Memcached服务器) |
SessionDAO | DAO大家都用过,数据访问对象,用于会话的CRUD,比如我们想把Session保存到数据库,那么可以实现自己的SessionDAO,通过如JDBC写到数据库;比如想把Session放到Memcached中,可以实现自己的Memcached SessionDAO;另外SessionDAO中可以使用Cache进行缓存,以提高性能 |
CacheManager | 缓存控制器,来管理如用户、角色、权限等的缓存的;因为这些数据基本上很少去改变,放到缓存中后可以提高访问的性能 |
Cryptography | 密码模块,Shiro提高了一些常见的加密组件用于如密码加密/解密的 |
(3)shiro名词解释
(4)shiro默认过滤器
当 Shiro 被运用到 web 项目时,Shiro 会自动创建一些默认的过滤器对客户端请求进行过滤。比如身份验证、授权等相关的操作。
过滤器 | 对应的 Java 类 |
---|---|
anon | org.apache.shiro.web.filter.authc.AnonymousFilter |
authc | org.apache.shiro.web.filter.authc.FormAuthenticationFilter |
authcBasic | org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter |
perms | org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter |
port | org.apache.shiro.web.filter.authz.PortFilter |
rest | org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter |
roles | org.apache.shiro.web.filter.authz.RolesAuthorizationFilter |
ssl | org.apache.shiro.web.filter.authz.SslFilter |
user | org.apache.shiro.web.filter.authc.UserFilter |
logout | org.apache.shiro.web.filter.authc.LogoutFilter |
noSessionCreation | org.apache.shiro.web.filter.session.NoSessionCreationFilter |
(5)对过滤器解释说明
- /admins/**=anon # 表示该 uri 可以匿名访问
- /admins/**=auth # 表示该 uri 需要认证才能访问
- /admins/**=authcBasic # 表示该 uri 需要 httpBasic 认证
- /admins/**=perms[user:add:] # 表示该 uri 需要认证用户拥有 user:add: 权限才能访问
- /admins/**=port[8081] # 表示该 uri 需要使用 8081 端口
- /admins/**=rest[user] # 相当于 /admins/=perms[user:method],其中,method 表示 get、post、delete 等
- /admins/**=roles[admin] # 表示该 uri 需要认证用户拥有 admin 角色才能访问
- /admins/**=ssl # 表示该 uri 需要使用 https 协议
- /admins/**=user # 表示该 uri 需要认证或通过记住我认证才能访问
- /logout=logout # 表示注销,可以当作固定配置
注意:
anon,authcBasic,auchc,user 是认证过滤器。
perms,roles,ssl,rest,port 是授权过滤器
(6)常见异常
shiro全局异常 :org.apache.shiro.ShiroException
shiro常见异常分为两大类:
1. AuthencationException:
AuthenticationException 异常是Shiro在登录认证过程中,认证失败需要抛出的异常。 AuthenticationException包含以下子类:
1.1 CredentitalsException 凭证异常及子类
IncorrectCredentialsException 不正确的凭证
ExpiredCredentialsException 凭证过期
1.2 AccountException 账号异常及子类
ConcurrentAccessException 并发访问异常(多个用户同时登录时抛出)
UnknownAccountException 未知的账号
ExcessiveAttemptsException 认证次数超过限制
DisabledAccountException 禁用的账号
LockedAccountException 账号被锁定
1.3 UnsupportedTokenException 使用了不支持的Token
2. AuthorizationException:
UnauthorizedException:抛出对请求的操作或对请求的资源的访问是不允许的
UnanthenticatedException:当未完成成功认证时,执行授权操作时引发异常
(7)shiro常见标签
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<!--xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">-->
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>首页</h1>
<!--
<shiro:guest></shiro:guest> 判断用户是否是游客身份,如果是,则显示此标签内容
<shiro:user></shiro:user> 判断用户是否是登录认证之后的,如果是,则显示此标签内容
<shiro:principal></shiro:principal> 获取当前登录的用户信息
-->
<shiro:guest>
欢迎游客访问,<a th:href="@{/toLogin}">登录</a>
</shiro:guest>
<!--从session中判断值-->
<!--<div th:if="${session.loginUser}!=null"></div>-->
<shiro:user>
用户[<h th:text="${session.loginUser.username}"></h>]欢迎您, <a th:href="@{/users/logout}">退出</a>
</shiro:user>
<p th:text="${msg}"></p>
<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>
</body>
</html>
二、ShiroConfig配置
1.配置Realm及多Realm的认证策略
多Realm认证策略: AuthenticationStrategy
• AuthenticationStrategy 接口的默认实现:
• FirstSuccessfulStrategy:只要有一个 Realm 验证成功即可,只返回第 一个 Realm 身份验证成功的认证信息,其他的忽略;
• AtLeastOneSuccessfulStrategy:只要有一个Realm验证成功即可,和 FirstSuccessfulStrategy 不同,将返回所有Realm身份验证成功的认证信 息;
• AllSuccessfulStrategy:所有Realm验证成功才算成功,且返回所有 Realm身份验证成功的认证信息,如果有一个失败就失败了。 • ModularRealmAuthenticator 默认是 AtLeastOneSuccessfulStrategy 策略
第一种写法:
/**
* 代表系统资源
* @return
*/
@Bean
public UserRealm userRealm() {
UserRealm userRealm = new UserRealm();
userRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return userRealm;
}
/**
* 代表系统资源
* @return
*/
@Bean
public MobileRealm mobileRealm() {
MobileRealm mobileRealm = new MobileRealm();
mobileRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return mobileRealm;
}
/**
* 流程控制
* @param userRealm
* @return
*/
@Bean
public DefaultWebSecurityManager securityManager(UserRealm userRealm,MobileRealm mobileRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//多Realm 配置认证策略
//AllSuccessfulStrategy所有realm都认证通过
//FirstSuccessfulStrategy 第一个Realm认证成功,后面的realm再不认证
//AtLeastOneSuccessfulStrategy 至少有一个realm认证通过
securityManager.setRealms(Arrays.asList(userRealm,mobileRealm));
//配置多Realm认证策略
ModularRealmAuthenticator modularRealmAuthenticator = new ModularRealmAuthenticator();
modularRealmAuthenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
modularRealmAuthenticator.setRealms(Arrays.asList(userRealm,mobileRealm));
securityManager.setAuthenticator(modularRealmAuthenticator);
return securityManager;
}
第二种写法:
/***
* 配置Realm
* */
@Bean
Realm userRealm() {
TestRealm userRealm = new TestRealm();
return userRealm;
}
/***
* 测试realm
* @return
*/
@Bean
Realm testRealm() {
return new TestRealm();
}
/**
* 多Realm认证策略
* @return
*/
@Bean
Authenticator authenticator() {
ModularRealmAuthenticator modularRealmAuthenticator = new ModularRealmAuthenticator();
//使用一个通过验证即可通过验证的方式
modularRealmAuthenticator.setAuthenticationStrategy(atLeastOneSuccessfulStrategy());
return modularRealmAuthenticator;
}
/**
* 所有reaml全都通过才算认证通过作为策略
* @return
*/
@Bean
AuthenticationStrategy allSuccessfulStrategy() {
AllSuccessfulStrategy allSuccessfulStrategy = new AllSuccessfulStrategy();
return allSuccessfulStrategy;
}
/**
* 所有reaml一个通过就算认证通过作为策略
* @return
*/
@Bean
AuthenticationStrategy atLeastOneSuccessfulStrategy() {
AtLeastOneSuccessfulStrategy atLeastOneSuccessfulStrategy = new AtLeastOneSuccessfulStrategy();
return atLeastOneSuccessfulStrategy;
}
2.配置RedisCacheManager和SeeionManager
2.1 引入依赖
<!-- 使用RedisProperties配置类-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- shiro+redis 做session和缓存控制-->
<dependency>
<groupId>org.crazycake</groupId>
<artifactId>shiro-redis</artifactId>
<version>3.3.1</version>
</dependency>
2.2 ShiroConfig中配置
@Bean
public RedisManager redisManager(){
RedisManager redisManager = new RedisManager();
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
//连接池最大量20,并发特别大时
jedisPoolConfig.setMaxTotal(redisProperties.getJedis().getPool().getMaxActive());
//连接池的最大剩余量15个,并发不大
jedisPoolConfig.setMaxIdle(redisProperties.getJedis().getPool().getMaxIdle());
//连接池初始就10个
jedisPoolConfig.setMinIdle(redisProperties.getJedis().getPool().getMinIdle());
JedisPool jedisPool = new JedisPool(jedisPoolConfig,redisProperties.getHost(),redisProperties.getPort(),2000,redisProperties.getPassword());
redisManager.setJedisPool(jedisPool);
return redisManager;
}
/**
* 缓存控制:shiro+redis实现
* @param redisManager
* @return
*/
@Bean
public RedisCacheManager redisCacheManager(RedisManager redisManager){
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager);
//针对不同用户进行缓存
redisCacheManager.setPrincipalIdFieldName("user");
//用户权限信息缓存时间 1800
redisCacheManager.setExpire(1800);
return redisCacheManager;
}
/**
* SessionDAO的作用是为Session提供CRUD并进行持久化的一个shiro组件
* @param redisManager
* @return
*/
@Bean
public RedisSessionDAO redisSessionDAO(RedisManager redisManager){
RedisSessionDAO sessionDAO = new RedisSessionDAO();
sessionDAO.setRedisManager(redisManager);
sessionDAO.setSessionIdGenerator(sessionIdGenerator());
//session在redis中保存的时间 1800
sessionDAO.setExpire(1800);
return sessionDAO;
}
@Bean
public DefaultWebSessionManager sessionManager(RedisSessionDAO redisSessionDAO){
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
sessionManager.setSessionDAO(redisSessionDAO);
//全局会话超时时间(单位毫秒),默认30分钟1800000
sessionManager.setGlobalSessionTimeout(600000);
//是否开启删除无效的session对象 默认为true
sessionManager.setDeleteInvalidSessions(true);
//是否开启定时调度器进行检测过期session 默认为true
sessionManager.setSessionValidationSchedulerEnabled(true);
//设置session失效的扫描时间, 清理用户直接关闭浏览器造成的孤立会话 默认为1个小时
sessionManager.setSessionValidationInterval(3600000);
//取消url 后面的 JSESSIONID
sessionManager.setSessionIdUrlRewritingEnabled(false);
return sessionManager;
}
3.配置securityManager
/**
* 流程控制器
* @param userRealm
* @return
*/
@Bean
public DefaultWebSecurityManager securityManager(UserRealm userRealm,
MobileRealm mobileRealm,
CookieRememberMeManager rememberMeManager,
RedisCacheManager redisCacheManager,
DefaultWebSessionManager sessionManager,
ModularRealmAuthenticator modularRealmAuthenticator,
MyModularRealmAuthenticator myModularRealmAuthenticator
) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//securityManager.setRealm(userRealm);
//记住我
securityManager.setRememberMeManager(rememberMeManager);
//缓存管理器
securityManager.setCacheManager(redisCacheManager);
//session管理器
securityManager.setSessionManager(sessionManager);
//认证策略(realm之前)
securityManager.setAuthenticator(modularRealmAuthenticator);
//securityManager.setAuthenticator(myModularRealmAuthenticator);
//多realm认证
securityManager.setRealms(Arrays.asList(userRealm,mobileRealm));
return securityManager;
}
4. 配置shiroFilterFactoryBean 其实就是Filter的规则
/**
* shiro内置请求过滤器
* @param securityManager
* @return
*/
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean (DefaultWebSecurityManager securityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//设置安全管理器
shiroFilterFactoryBean.setSecurityManager(securityManager);
//添加内置过滤器,设置拦截规则
Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>();
//设置登录请求页面
shiroFilterFactoryBean.setLoginUrl("/toLogin");
//设置登出请求页面
filterChainDefinitionMap.put("/logout","logout");
//设置未授权页面
shiroFilterFactoryBean.setUnauthorizedUrl("/unathorized");
//先对系统资源进行授权访问
filterChainDefinitionMap.put("/user/add","perms[sys:c:save]");
//配置路径过滤器,key时ant路径,**表示多级路径,*表示一级路径,?表示一个字符
//user过滤器表示记住我才能访问(已认证也可以访问)
filterChainDefinitionMap.put("/index","user");
filterChainDefinitionMap.put("/user/*","anon");
filterChainDefinitionMap.put("/**","authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
5. 配置凭证匹配器
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher(){
//密码加密
HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
//设置加密算法
matcher.setHashAlgorithmName("MD5");
//设置迭代次数 eg: 123--md5->abc--md5->xyz--md5->??? 即设置密码经过多少次MD5加密
matcher.setHashIterations(3);
return matcher;
}
/**
* 代表系统资源
* @return
*/
@Bean
public UserRealm userRealm() {
UserRealm userRealm = new UserRealm();
userRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return userRealm;
}
/**
* 代表系统资源
* @return
*/
@Bean
public MobileRealm mobileRealm() {
MobileRealm mobileRealm = new MobileRealm();
mobileRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return mobileRealm;
}
6. 配置RememberMe
6.1 登陆页面
<div class="layui-container">
<div class="admin-login-background">
<div class="layui-form login-form">
<form class="layui-form" method="post" action="">
<div class="layui-form-item logo-title">
<h1>后台登录</h1>
</div>
<div class="layui-form-item">
<label class="layui-icon layui-icon-username" ></label>
<input type="text" name="username" lay-verify="required" placeholder="用户名" autocomplete="off" class="layui-input" value="zkc">
</div>
<div class="layui-form-item">
<label class="layui-icon layui-icon-password" ></label>
<input type="password" name="password" lay-verify="required" placeholder="密码" autocomplete="off" class="layui-input" value="123456">
</div>
<div class="layui-form-item">
账号密码登录<input type="radio" name="loginType" value="User" checked />
手机号登录<input type="radio" name="loginType" value="Mobile" />
</div>
<div class="layui-form-item">
<!--checkbox默认值-->
<input type="hidden" name="rememberMe" value="false">
<input type="checkbox" name="rememberMe" value="true" lay-skin="primary" title="记住密码">
</div>
<div class="layui-form-item">
<button class="layui-btn layui-btn-fluid" lay-submit="" lay-filter="login">登 录</button>
</div>
</form>
</div>
</div>
</div>
6.2 登录接口
@PostMapping("/user/login")
@ResponseBody
public JsonResult login(@Validated LoginDto loginDto,Model model){
log.info("========enter method UserController-login");
//获取当前用户
Subject subject = SecurityUtils.getSubject();
//封装用户登录数据
UsernamePasswordToken token = new UsernamePasswordToken(loginDto.getUsername(), loginDto.getPassword());
log.info("RememberMe type========"+loginDto.getRememberMe());
//用自定义token进行登录
//MyToken token = new MyToken(loginDto.getUsername(),loginDto.getPassword(),loginDto.getLoginType());
if(loginDto.getRememberMe()){
token.setRememberMe(true);
}
try {
subject.login(token);
model.addAttribute("username",token.getUsername());
return new JsonResult();
} catch (UnknownAccountException e) {
return new JsonResult().error("账户不存在");
}catch (IncorrectCredentialsException e){
return new JsonResult().error("密码不正确");
}
}
6.3 ShiroConfig配置
/**
* @return
* 在shiro应用做了记住我功能,而这个功能在服务端通过cookie存储账号信息时,
* 会对账号信息进行Base64加密,在加密时会创建一把密钥,密钥在服务端重启时会丢失,
* 当我们再次通过浏览器访问服务时,因为客户端存储账号信息的cookie还是有效的,
* 所以浏览器依旧会携带cookie到服务端,但是服务端解密cookie信息的密钥丢失,
* 所以不能完成解密操作,就会出现异常,这种异常只会在程序重启(shiro清除session)第一次打开页面的时候出现
*/
@Bean
public CookieRememberMeManager cookieRememberMeManager (){
//记住我功能,登录之后在配置时间内,关闭浏览器之后,访问配置的user过滤器的资源时不需要再认证直接可以访问的
CookieRememberMeManager rememberMeManager = new CookieRememberMeManager();
SimpleCookie cookie = new SimpleCookie("rememberMe");
cookie.setHttpOnly(true);
cookie.setMaxAge(31536000);
cookie.setPath("/");
rememberMeManager.setCookie(cookie);
//指定cookie的主动设置cipherkey 加密解密密钥
rememberMeManager.setCipherKey(Base64.getDecoder().decode(Constants.REMEMBERME_DECODE_KEY));
return rememberMeManager;
}
三、测试代码案例
1. shiro认证流程
• 1、首先调用 Subject.login(token) 进行登录,其会自动委托给 SecurityManager
• 2、SecurityManager 负责真正的身份验证逻辑;它会委托给 Authenticator 进行身份验证;
• 3、Authenticator 才是真正的身份验证者,Shiro API 中核心的身份 认证入口点,此处可以自定义插入自己的实现;
• 4、Authenticator 可能会委托给相应的 AuthenticationStrategy 进 行多 Realm 身份验证,默认 ModularRealmAuthenticator 会调用 AuthenticationStrategy 进行多 Realm 身份验证;
• 5、Authenticator 会把相应的 token 传入 Realm,从 Realm 获取 身份验证信息,如果没有返回/抛出异常表示身份验证失败了。此处 可以配置多个Realm,将按照相应的顺序及策略进行访问。
2.Realm的认证和授权
2.1 UserRealm
public class Constants {
public static final String SALT = "!QAZ@WSX";
public static final String REMEMBERME_DECODE_KEY = "6ZmI6I2j5Y+R5aSn5ZOlAA==";
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginUserProfile implements Serializable {
private static final long serialVersionUID = -6725793787701776691L;
private User user;
private Set<String> roles;
private Set<String> permissions;
}
public class UserRealm extends AuthorizingRealm {
public static final Logger log = LoggerFactory.getLogger(UserRealm.class);
@Lazy
@Autowired
UserMapper userMapper;
@Lazy
@Autowired
RoleService roleService;
@Lazy
@Autowired
PermissionService permissionService;
public String getName(){
return "UserRealm";
}
/**
* 授权
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
log.info("============>查询角色和权限信息");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
Subject subject = SecurityUtils.getSubject();
//获取当前用户信息
LoginUserProfile profile = (LoginUserProfile) subject.getPrincipal();
//查询角色
Set<String> roleNameList = roleService.getRoleNamesByUserId(profile.getUser().getId());
//查询权限
Set<String> permissionCodeList = permissionService.getPermissionsByUsername(profile.getUser().getUsername());
profile.setRoles(roleNameList);
profile.setPermissions(permissionCodeList);
//设置当前用户的角色和权限
info.setRoles(roleNameList);
info.setStringPermissions(permissionCodeList);
return info;
}
/**
* 认证
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
log.info("================enter method UserRealm-doGetAuthenticationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
LoginUserProfile profile = new LoginUserProfile();
//查询用户
User user = userMapper.getUserByUsername(userToken.getUsername());
if(null == user){
throw new UnknownAccountException("账号不存在");
}
profile.setUser(user);
SecurityUtils.getSubject().getSession().setAttribute("loginUser",profile);
//加salt返回
ByteSource salt = ByteSource.Util.bytes(Constants.SALT);
return new SimpleAuthenticationInfo(profile,user.getPassword(),salt,getName());
}
}
2.2 MobileRealm
@Slf4j
public class MobileRealm extends AuthenticatingRealm {
@Lazy
@Autowired
UserMapper userMapper;
public String getName(){
return "MobileRealm";
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
log.info("===============enter method MobileRealm-doGetAuthenticationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
LoginUserProfile profile = new LoginUserProfile();
//查询
User user = userMapper.getUserByPhone(userToken.getUsername());
if(user == null){
throw new UnknownAccountException("账户不存在");
}
profile.setUser(user);
SecurityUtils.getSubject().getSession().setAttribute("loginUser",user);
//加salt返回
ByteSource salt = ByteSource.Util.bytes(Constants.SALT);
return new SimpleAuthenticationInfo(profile,user.getPassword(),salt,getName());
}
}
3.shiro的授权方式
规则:
(1)编程式:通过if/else授权代码块完成
if(subject.hasRole(“admin”)){有权限}else{无权限}
(2)注解式:
通过在方法上使用相应的注解来完成,没有权限将抛出相应异常
开启注解:
/**
*
* @param securityManager
* @return
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager){
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager);
return advisor;
}
@Bean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
autoProxyCreator.setProxyTargetClass(true);
return autoProxyCreator;
}
注解式抛出的异常用SpringBoot统一异常处理来拦截
@RestControllerAdvice
public class GlobalExceptionHandle {
@ExceptionHandler(value = ShiroException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public ErrorResult handleShiroException(ShiroException e){
log.info("登录时异常---------->{}",e.getMessage());
return new ErrorResult(401,e.getMessage());
}
}
或者可以返回到指定的错误页面
@ControllerAdvice
public class GlobalExceptionHandle {
@ExceptionHandler(value = Exception.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String handleShiroException(Exception e){
if(e instanceof AuthorizationException){
return "error";
}
return null;
}
(3)过滤器中配置
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean (DefaultWebSecurityManager securityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//设置安全管理器
shiroFilterFactoryBean.setSecurityManager(securityManager);
//添加内置过滤器,设置拦截规则
Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>();
//设置登录请求页面
shiroFilterFactoryBean.setLoginUrl("/toLogin");
//设置登出请求页面
filterChainDefinitionMap.put("/logout","logout");
//设置未授权页面
shiroFilterFactoryBean.setUnauthorizedUrl("/unathorized");
//先对系统资源进行授权访问
filterChainDefinitionMap.put("/user/add","perms[sys:c:save]");
//配置路径过滤器,key时ant路径,**表示多级路径,*表示一级路径,?表示一个字符
filterChainDefinitionMap.put("/user/*","anon");
filterChainDefinitionMap.put("/**","authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
(4)使用标签形式
- 先配置加入标签使用的依赖
<!--shiro+thymeleaf-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
- shiro配置文件中配置方言
/**
* 整合shiro+thymeleaf,可以使用shiro:hasPermission 等标签
* @return
*/
@Bean
public ShiroDialect shiroDialect(){
return new ShiroDialect();
}
- html 标签添加
<!DOCTYPE html>
<html xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
- 使用shiro标签
<shiro:hasPermission name="sys:x:save">
<dd><a href="javascript:">添加订单</a></dd>
</shiro:hasPermission>
3.完整版ShiroConfig配置类
@Configuration
public class ShiroConfig {
@Autowired
RedisProperties redisProperties;
/**
* 凭证匹配器
* @return
*/
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher(){
//密码加密
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
//设置加密算法
hashedCredentialsMatcher.setHashAlgorithmName("MD5");
//设置迭代次数 eg: 123--md5->abc--md5->xyz--md5->??? 即设置密码经过多少次MD5加密
hashedCredentialsMatcher.setHashIterations(3);
return hashedCredentialsMatcher;
}
/**
* 代表系统资源
* @return
*/
@Bean
public UserRealm userRealm(HashedCredentialsMatcher hashedCredentialsMatcher) {
UserRealm userRealm = new UserRealm();
userRealm.setCredentialsMatcher(hashedCredentialsMatcher);
return userRealm;
}
/**
* 代表系统资源
* @return
*/
@Bean
public MobileRealm mobileRealm(HashedCredentialsMatcher hashedCredentialsMatcher) {
MobileRealm mobileRealm = new MobileRealm();
mobileRealm.setCredentialsMatcher(hashedCredentialsMatcher);
return mobileRealm;
}
/**
* 多个Realm认证策略
* AllSuccessfulStrategy所有realm都认证通过
* FirstSuccessfulStrategy 第一个Realm认证成功,后面的realm再不认证
* AtLeastOneSuccessfulStrategy 至少有一个realm认证通过
* @param userRealm
* @param mobileRealm
* @return
*/
@Bean
public ModularRealmAuthenticator modularRealmAuthenticator(UserRealm userRealm,MobileRealm mobileRealm){
//配置多Realm认证策略
ModularRealmAuthenticator modularRealmAuthenticator = new ModularRealmAuthenticator();
modularRealmAuthenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
modularRealmAuthenticator.setRealms(Arrays.asList(userRealm,mobileRealm));
return modularRealmAuthenticator;
}
/**
* 自定义认证器
* @return
*/
@Bean
public MyModularRealmAuthenticator myModularRealmAuthenticator(){
return new MyModularRealmAuthenticator();
}
/**
* @return
* 在shiro应用做了记住我功能,而这个功能在服务端通过cookie存储账号信息时,
* 会对账号信息进行Base64加密,在加密时会创建一把密钥,密钥在服务端重启时会丢失,
* 当我们再次通过浏览器访问服务时,因为客户端存储账号信息的cookie还是有效的,
* 所以浏览器依旧会携带cookie到服务端,但是服务端解密cookie信息的密钥丢失,
* 所以不能完成解密操作,就会出现异常,这种异常只会在程序重启(shiro清除session)第一次打开页面的时候出现
*/
@Bean
public CookieRememberMeManager cookieRememberMeManager (){
//记住我功能,登录之后在配置时间内,关闭浏览器之后,访问配置的user过滤器的资源时不需要再认证直接可以访问的
CookieRememberMeManager rememberMeManager = new CookieRememberMeManager();
SimpleCookie cookie = new SimpleCookie("rememberMe");
cookie.setHttpOnly(true);
cookie.setMaxAge(31536000);
cookie.setPath("/");
rememberMeManager.setCookie(cookie);
//指定cookie的主动设置cipherkey 加密解密密钥
rememberMeManager.setCipherKey(Base64.getDecoder().decode(Constants.REMEMBERME_DECODE_KEY));
return rememberMeManager;
}
/**
* 缓存控制:比如第一次进行授权时查询数据库权限之后,接下来的操作再不用去数据库查询权限
* @return
*/
@Bean
public MemoryConstrainedCacheManager cacheManager(){
return new MemoryConstrainedCacheManager();
}
/**
* 缓存控制:shiro+redis实现
* setPrincipalIdFieldName("")这里传的值是UserRealm认证后返回的SimpleAuthenticationInfo的第一个参数的属性
* 比如:我在Realm认证里传的LoginuserProfile对象,则在这里传对象里的user属性
* 如果第一个参数传的是实体,则此处传的是通过该参数能唯一查到该条实体数据的参数;传实体时这里默认是该实体的id字段
* 如果第一个参数传的是username或者其他单个参数,则这里直接用同样的参数即可
* @param redisManager
* @return
*/
@Bean
public RedisCacheManager redisCacheManager(RedisManager redisManager){
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager);
//针对不同用户进行缓存
redisCacheManager.setPrincipalIdFieldName("user");
//用户权限信息缓存时间 1800
redisCacheManager.setExpire(1800);
return redisCacheManager;
}
/**
* SessionDAO的作用是为Session提供CRUD并进行持久化的一个shiro组件
* @param redisManager
* @return
*/
@Bean
public RedisSessionDAO redisSessionDAO(RedisManager redisManager){
RedisSessionDAO sessionDAO = new RedisSessionDAO();
sessionDAO.setRedisManager(redisManager);
sessionDAO.setSessionIdGenerator(sessionIdGenerator());
//session在redis中保存的时间 1800
sessionDAO.setExpire(1800);
return sessionDAO;
}
@Bean
public DefaultWebSessionManager sessionManager(RedisSessionDAO redisSessionDAO){
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
sessionManager.setSessionDAO(redisSessionDAO);
//全局会话超时时间(单位毫秒),默认30分钟1800000
sessionManager.setGlobalSessionTimeout(600000);
//是否开启删除无效的session对象 默认为true
sessionManager.setDeleteInvalidSessions(true);
//是否开启定时调度器进行检测过期session 默认为true
sessionManager.setSessionValidationSchedulerEnabled(true);
//设置session失效的扫描时间, 清理用户直接关闭浏览器造成的孤立会话 默认为1个小时
sessionManager.setSessionValidationInterval(3600000);
//取消url 后面的 JSESSIONID
sessionManager.setSessionIdUrlRewritingEnabled(false);
return sessionManager;
}
/**
* 流程控制器
* @param userRealm
* @return
*/
@Bean
public DefaultWebSecurityManager securityManager(UserRealm userRealm,
MobileRealm mobileRealm,
CookieRememberMeManager rememberMeManager,
RedisCacheManager redisCacheManager,
DefaultWebSessionManager sessionManager,
ModularRealmAuthenticator modularRealmAuthenticator,
MyModularRealmAuthenticator myModularRealmAuthenticator
) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//securityManager.setRealm(userRealm);
//记住我
securityManager.setRememberMeManager(rememberMeManager);
//缓存管理器
securityManager.setCacheManager(redisCacheManager);
//session管理器
securityManager.setSessionManager(sessionManager);
//认证策略(realm之前)
securityManager.setAuthenticator(modularRealmAuthenticator);
//securityManager.setAuthenticator(myModularRealmAuthenticator);
//多realm认证
securityManager.setRealms(Arrays.asList(userRealm,mobileRealm));
return securityManager;
}
/**
* shiro内置请求过滤器
* @param securityManager
* @return
*/
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean (DefaultWebSecurityManager securityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//设置安全管理器
shiroFilterFactoryBean.setSecurityManager(securityManager);
//添加内置过滤器,设置拦截规则
Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>();
//设置登录请求页面
shiroFilterFactoryBean.setLoginUrl("/toLogin");
//设置登出请求页面
filterChainDefinitionMap.put("/logout","logout");
//设置未授权页面
shiroFilterFactoryBean.setUnauthorizedUrl("/unathorized");
//先对系统资源进行授权访问
filterChainDefinitionMap.put("/user/add","perms[sys:c:save]");
//配置路径过滤器,key时ant路径,**表示多级路径,*表示一级路径,?表示一个字符
//user过滤器表示记住我才能访问(已认证也可以访问)
filterChainDefinitionMap.put("/index","user");
filterChainDefinitionMap.put("/user/*","anon");
filterChainDefinitionMap.put("/**","authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
@Bean
public RedisManager redisManager(){
RedisManager redisManager = new RedisManager();
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
//连接池最大量20,并发特别大时
jedisPoolConfig.setMaxTotal(redisProperties.getJedis().getPool().getMaxActive());
//连接池的最大剩余量15个,并发不大
jedisPoolConfig.setMaxIdle(redisProperties.getJedis().getPool().getMaxIdle());
//连接池初始就10个
jedisPoolConfig.setMinIdle(redisProperties.getJedis().getPool().getMinIdle());
JedisPool jedisPool = new JedisPool(jedisPoolConfig,redisProperties.getHost(),redisProperties.getPort(),2000,redisProperties.getPassword());
redisManager.setJedisPool(jedisPool);
return redisManager;
}
/**
* Session ID 生成器
*
* @return JavaUuidSessionIdGenerator
*/
@Bean
public JavaUuidSessionIdGenerator sessionIdGenerator() {
return new JavaUuidSessionIdGenerator();
}
/* 加入注解的使用,不加入这个注解不生效--开始 */
/**
*
* @param securityManager
* @return
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager){
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager);
return advisor;
}
@Bean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
autoProxyCreator.setProxyTargetClass(true);
return autoProxyCreator;
}
/* 加入注解的使用,不加入这个注解不生效--结束 */
/**
* 整合shiro+thymeleaf,可以使用shiro:hasPermission 等标签
* @return
*/
@Bean
public ShiroDialect shiroDialect(){
return new ShiroDialect();
}
}
4. 完整yml文件
server:
port: 8888
spring:
datasource:
url: jdbc:mysql://121.41.106.140:3306/shiroDB?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
type: com.alibaba.druid.pool.DruidDataSource
#redis配置
redis:
host: 121.41.106.140
port: 6379
password: r123456
jedis:
pool:
max-wait: 2000 #连接池最大阻塞等待时间,负值表示没有限制
max-active: 20 #连接池中的最大连接数,负值表示没有限制,默认为8
max-idle: 8 #连接池中最大的空闲连接数
min-idle: 0 #连接池中最小的空闲连接数
mybatis-plus:
mapper-locations: classpath*:/mapper/**Mapper.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
5. 完整pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zjhc</groupId>
<artifactId>springboot-shiro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>springboot-shiro</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.7.1</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>5.1.47</scope>
</dependency>
<!-- mybatis plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.23</version>
</dependency>
<!--hutool工具包-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.7</version>
</dependency>
<!-- thymeleaf 模板-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<!--shiro+thymeleaf-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
<!-- shiro+redis 做session和缓存控制-->
<dependency>
<groupId>org.crazycake</groupId>
<artifactId>shiro-redis</artifactId>
<version>3.3.1</version>
</dependency>
<!-- Hibernate Validate-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
四、自定义认证器进行多Realm认证
1. 重写token继承UsernamePasswordToken
public class MyToken extends UsernamePasswordToken {
private static final long serialVersionUID = -3038706751607520819L;
private String loginType;
public MyToken(String username, String password, String loginType) {
super(username, password);
this.loginType = loginType;
}
public String getLoginType() {
return loginType;
}
public void setLoginType(String loginType) {
this.loginType = loginType;
}
2. 重写认证器集成ModularRealmAuthenticator
@Slf4j
public class MyModularRealmAuthenticator extends ModularRealmAuthenticator {
@Override
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
log.info("===============进入自定义认证器MyModularRealmAuthenticator");
this.assertRealmsConfigured();
Collection<Realm> realms = this.getRealms();
Collection<Realm> realmList = new ArrayList<>();
MyToken token = (MyToken) authenticationToken;
String loginType = token.getLoginType();
for(Realm realm : realms){
if(realm.getName().startsWith(loginType)){
realmList.add(realm);
}
}
if(realmList.size() == 1){
return this.doSingleRealmAuthentication((Realm) realmList.iterator().next(),authenticationToken);
}else{
return this.doMultiRealmAuthentication(realmList,authenticationToken);
}
}
}
3. ShiroConfig中进行配置自定义认证器
/**
* 自定义认证器
* @return
*/
@Bean
public MyModularRealmAuthenticator myModularRealmAuthenticator(){
return new MyModularRealmAuthenticator();
}
4. SecurityManager中进行配置
/**
* 流程控制器
* @param userRealm
* @return
*/
@Bean
public DefaultWebSecurityManager securityManager(UserRealm userRealm,
MobileRealm mobileRealm,
CookieRememberMeManager rememberMeManager,
RedisCacheManager redisCacheManager,
DefaultWebSessionManager sessionManager,
ModularRealmAuthenticator modularRealmAuthenticator,
MyModularRealmAuthenticator myModularRealmAuthenticator
) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//securityManager.setRealm(userRealm);
//记住我
securityManager.setRememberMeManager(rememberMeManager);
//缓存管理器
securityManager.setCacheManager(redisCacheManager);
//session管理器
securityManager.setSessionManager(sessionManager);
//认证策略(realm之前)
//securityManager.setAuthenticator(modularRealmAuthenticator);
securityManager.setAuthenticator(myModularRealmAuthenticator);
//多realm认证
securityManager.setRealms(Arrays.asList(userRealm,mobileRealm));
return securityManager;
}
5. 登录接口
@PostMapping("/user/login")
@ResponseBody
public JsonResult login(@Validated LoginDto loginDto,Model model){
log.info("========enter method UserController-login");
//获取当前用户
Subject subject = SecurityUtils.getSubject();
//封装用户登录数据
//UsernamePasswordToken token = new UsernamePasswordToken(loginDto.getUsername(), loginDto.getPassword());
log.info("RememberMe type========"+loginDto.getRememberMe());
//用自定义token进行登录
MyToken token = new MyToken(loginDto.getUsername(),loginDto.getPassword(),loginDto.getLoginType());
if(loginDto.getRememberMe()){
token.setRememberMe(true);
}
try {
subject.login(token);
model.addAttribute("username",token.getUsername());
return new JsonResult();
} catch (UnknownAccountException e) {
return new JsonResult().error("账户不存在");
}catch (IncorrectCredentialsException e){
return new JsonResult().error("密码不正确");
}
}
6. 页面
<div class="layui-container">
<div class="admin-login-background">
<div class="layui-form login-form">
<form class="layui-form" method="post" action="">
<div class="layui-form-item logo-title">
<h1>后台登录</h1>
</div>
<div class="layui-form-item">
<label class="layui-icon layui-icon-username" ></label>
<input type="text" name="username" lay-verify="required" placeholder="用户名" autocomplete="off" class="layui-input" value="zkc">
</div>
<div class="layui-form-item">
<label class="layui-icon layui-icon-password" ></label>
<input type="password" name="password" lay-verify="required" placeholder="密码" autocomplete="off" class="layui-input" value="123456">
</div>
<div class="layui-form-item">
账号密码登录<input type="radio" name="loginType" value="User" checked />
手机号登录<input type="radio" name="loginType" value="Mobile" />
</div>
<div class="layui-form-item">
<!--checkbox默认值-->
<input type="hidden" name="rememberMe" value="false">
<input type="checkbox" name="rememberMe" value="true" lay-skin="primary" title="记住密码">
</div>
<div class="layui-form-item">
<button class="layui-btn layui-btn-fluid" lay-submit="" lay-filter="login">登 录</button>
</div>
</form>
</div>
</div>
</div>
五、统一返回处理
@Data
public class JsonResult<T> implements Serializable {
private int code;
private String msg;
private T data;
public JsonResult(){
this.code = 200;
this.msg = "操作成功";
}
public JsonResult(String msg){
this.code = 200;
this.msg = msg;
}
public JsonResult(int code,String msg){
this.code = code;
this.msg = msg;
}
public JsonResult(T data){
this.code = 200;
this.msg = "操作成功";
this.data = data;
}
public JsonResult(T data,String msg){
this.code = 200;
this.msg = msg;
this.data = data;
}
public JsonResult success(T data){
JsonResult<T> result = new JsonResult<>();
result.setCode(200);
result.setMsg("操作成功");
result.setData(data);
return result;
}
public JsonResult success(T data,String msg){
JsonResult<T> result = new JsonResult<>();
result.setCode(200);
result.setMsg(msg);
result.setData(data);
return result;
}
public JsonResult error(String msg){
JsonResult<T> result = new JsonResult<>();
result.setCode(-1);
result.setMsg(msg);
result.setData(null);
return result;
}
}
六、统一异常处理
@Data
public class ErrorResult implements Serializable {
private int code;
private String msg;
public ErrorResult(String msg){
this.msg = msg;
}
public ErrorResult(int code, String msg){
this.code = code;
this.msg = msg;
}
}
6.1 shiro使用注解权限时异常处理
6.1.1 springboot项目中解决方法
使用注解时shiroFilterFactoryBean.setUnauthorizedUrl无效,无权限或者没登录时页面不跳转,展示不友好页面。
Shiro注解模式下,访问权限注解管理的接口时,没有登录、登录失败与没有权限都是通过抛出异常的,需要用springboot统一异常处理来捕获处理
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandle {
@ExceptionHandler(value = AuthorizationException.class)
public String handleAuthorizationException(AuthorizationException e){
if(e instanceof UnauthorizedException){
log.info("shiro-UnauthorizedException---------->{}",e.getMessage());
return "redirect:/unathorized";
}else if(e instanceof UnauthenticatedException){
log.info("shiro-UnauthenticatedException---------->{}",e.getMessage());
return "redirect:/toLogin";
}
return null;
}
@ExceptionHandler(value = ShiroException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public ErrorResult handleShiroException(ShiroException e){
log.info("shiro异常{}---------->{}",e,e.getMessage());
return new ErrorResult(401,e.getMessage());
}
@ExceptionHandler(ValidationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResult handleValidationException(ValidationException e){
log.info("参数校验异常------------>{}",e.getMessage());
return new ErrorResult(400,e.getMessage());
}
@ExceptionHandler(value = BindException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResult handleMethodArgumentNotValidException(BindException e){
/*
筛选错误信息,错误信息有多个时,返回一个集合
*/
BindingResult bindingResult = e.getBindingResult();
ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
log.info("实体校验异常---------->{}",objectError.getDefaultMessage());
return new ErrorResult(400,objectError.getDefaultMessage());
}
@ExceptionHandler(value = IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResult handleIllegalArgumentException(IllegalArgumentException e){
log.info("不合法的参数异常---------->{}",e.getMessage());
return new ErrorResult(400,e.getMessage());
}
@ExceptionHandler(value = RuntimeException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResult handleRuntimeException(RuntimeException e){
log.info("运行时异常---------->{}",e.getMessage());
return new ErrorResult(400,e.getMessage());
}
}
6.1.2 springMVC项目中解决方法
在ShiroConfig配置文件中配置
/**
* 解决:无权限页面不跳转,shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized") 无效
* Shiro注解模式下,登录失败与没有权限都是通过抛出异常
*
* @return
*/
@Bean
public SimpleMappingExceptionResolver simpleMappingExceptionResolver() {
SimpleMappingExceptionResolver simpleMappingExceptionResolver=new SimpleMappingExceptionResolver();
Properties properties=new Properties();
//这里的unauthorized 是页面,不是访问的路径
properties.setProperty("org.apache.shiro.authz.UnauthorizedException","unathorized");
properties.setProperty("org.apache.shiro.authz.UnauthenticatedException","unathorized");
simpleMappingExceptionResolver.setExceptionMappings(properties);
return simpleMappingExceptionResolver;
}
6.2 shiro处理访问不存在的资源或者服务器异常错误
/**
* 访问不存在的后台服务,如/userInfo/adddfdsafsafsa 这样后面随便乱打的,
* 这种情况,依然还是返回了Whitelabel Error Page页面,我们不想看到这种效果
* 把页面必须放在resource/static下面,不然访问不到
* @return
*/
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
@Override
public void customize(ConfigurableWebServerFactory factory) {
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/errorPage/404.html");
ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/errorPage/500.html");
factory.addErrorPages(error404Page,error500Page);
}
};
}
七、常见问题处理
7.1 org.crazycake.shiro.exception.SerializationException: serialize error, object=
出现这种情况是因为:SimpleByteSource没有是实现Serializable接口
解决办法:
- 取消authenticationCache在上面的 shiroRealm 配置中 我们开启了两个缓存:authenticationCache 和 authorizationCache 序列化失败的原因就是 因为开启了 authenticationCache 可以将 authenticationCache对应的那两行配置 删除,只缓存 authorizationCache
- 自定义一个类继承SimpleByteSource实现Serializable接口
当然也可以实现ByteSource接口和Serializable接口,但是实现ByteSource接口需要实现其方法,不方便。
自定义一个SimpleByteSource 类继承继承SimpleByteSource实现Serializable接口
public class SimpleByteSource extends org.apache.shiro.util.SimpleByteSource implements Serializable {
private static final long serialVersionUID = 7220896367594761367L;
public SimpleByteSource(byte[] bytes) {
super(bytes);
}
}
创建工具类ByteSourceUtils
public class ByteSourceUtils {
public static ByteSource bytes(byte[] bytes){
return new SimpleByteSource(bytes);
}
public static ByteSource bytes(String arg0){
return new SimpleByteSource(arg0.getBytes());
}
}
最后在Realm认证方法中
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
log.info("=====================enter method UserRealm-doGetAuthenticationInfo进行登陆验证");
UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
LoginUserProfile profile = new LoginUserProfile();
//查询用户
User user = userMapper.getUserByUsername(userToken.getUsername());
if(null == user){
throw new UnknownAccountException("账号不存在,请重试");
}
profile.setUser(user);
SecurityUtils.getSubject().getSession().setAttribute("loginUser",profile);
//加salt返回
//ByteSource salt = ByteSource.Util.bytes(Constants.SALT);
ByteSource salt = ByteSourceUtils.bytes(Constants.SALT);
return new SimpleAuthenticationInfo(profile,user.getPassword(),salt,getName());
}
- 将SimpleByteSource整个类 复制粘贴 给个名字 叫MyByteSource,额外实现Serializable接口,并添加无参构造器
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 MyByteSource.BytesHelper().getBytes(file);
}
public MyByteSource(InputStream stream) {
this.bytes = new MyByteSource.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;
}
@Override
public byte[] getBytes() {
return this.bytes;
}
@Override
public boolean isEmpty() {
return this.bytes == null || this.bytes.length == 0;
}
@Override
public String toHex() {
if ( this.cachedHex == null ) {
this.cachedHex = Hex.encodeToString(getBytes());
}
return this.cachedHex;
}
@Override
public String toBase64() {
if ( this.cachedBase64 == null ) {
this.cachedBase64 = Base64.encodeToString(getBytes());
}
return this.cachedBase64;
}
@Override
public String toString() {
return toBase64();
}
@Override
public int hashCode() {
if (this.bytes == null || this.bytes.length == 0) {
return 0;
}
return Arrays.hashCode(this.bytes);
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof ByteSource) {
ByteSource bs = (ByteSource) o;
return Arrays.equals(getBytes(), bs.getBytes());
}
return false;
}
//will probably be removed in Shiro 2.0. See SHIRO-203:
//https://issues.apache.org/jira/browse/SHIRO-203
private static final class BytesHelper extends CodecSupport {
/**
* 嵌套类也需要提供无参构造器
*/
private BytesHelper() {
}
public byte[] getBytes(File file) {
return toBytes(file);
}
public byte[] getBytes(InputStream stream) {
return toBytes(stream);
}
}
}
7.2 No SecurityManager accessible to the calling code
原因:formAuthenticationFilter 在shiroFilterFactoryBean前面加载,而后使用
SecurityUtils.getSubject()时会报这个错,应该放后面去加载;
注意:自定义filter也应该在shiroFilter之后加载;如果将自定义的Filter在ShiroFitler之前加载,ShiroFilter 是整个 Shiro 的入口点,用于拦截需要安全控制的请求进行处理,当自定义的filter先于shiroFilter加载,而shiroFilter里又使用到该自定义filter时,就会导致调用该自定义filter进行预处理时访问不到SecurityManager
7.3 rememberMe时,Userinfo必须实现序列化接口
UserInfo实体类必须实现序列化接口,否则报序列化异常。因为RememberMe会将用户信息加密然后以Cookie保存
7.4 xxxx is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)解决
在使用shiro时,ShiroFilterFactoryBean 会依赖注入 securityManager 然后 securityManager 会注入自定义 Realm ,然后自定义Realm类里面会注入业务的service类,而那些service类包含事务,都是动态代理类。因此无法注入,大致异常为:xxxx is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
解决方法:
- 在字段上加@Lazy(推荐)
import org.springframework.context.annotation.Lazy;
import org.apache.shiro.realm.AuthorizingRealm;
public class DatabaseRealm extends AuthorizingRealm {
@Lazy
@Autowired
private UserService userService;
- 加到构造方法的参数上
import org.springframework.context.annotation.Lazy;
import org.apache.shiro.realm.AuthorizingRealm;
public class DatabaseRealm extends AuthorizingRealm {
private UserService userService;
public DatabaseRealm(@Lazy @Autowired UserService userService){
this.userService = userService;
}
}
- 使用hutool工具类下的SpringUtil
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
**MUserService userService = SpringUtil.getBean(MUserService.class);**
MUser user = userService.getOneUser(userToken.getUsername());
if(user == null){
throw new UnknownAccountException("账户不存在");
}
return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
}
- 在Shiro框架中注入Bean时,不使用@Autowire,使用ApplicationContextRegister.getBean()方法,手动注入bean。保证该方法只有在程序完全启动运行时,才被注入
7.5 事务失效的解决方法
由于shiro的bean先于Spring事务将userService实例化了,结果导致spring事务初始化时好无法扫描到该bean,导致这个bean上没有绑定事务,导致事务无效,报错如下:
- 在字段上加@Lazy(推荐)
import org.springframework.context.annotation.Lazy;
import org.apache.shiro.realm.AuthorizingRealm;
public class DatabaseRealm extends AuthorizingRealm {
@Lazy
@Autowired
private UserService userService;
- orm映射框架的Mapper类,不是由Spring生成初始化,只是交给Spring管理,不会影响Spring bean的初始化
public class UserRealm extends AuthorizingRealm {
@Autowired
private SysUserMapper sysUserMapper;
@Autowired
private SysPermissionMapper sysPermissionMapper;
}
- 在service实现层的类或者public方法上添加@Transactionl注解