今天介绍shiro安全框架的应用,主要简介登录相关,权限控制此次不做讲解.项目框架为Springboot,Maven管理jar包.(万字,要有耐心喔)
1.maven引入shiro相关依赖
<dependency>
<groupId>org.apache.shirogroupId>
<artifactId>shiro-springartifactId>
<version>${shiro-spring.version}version>
dependency>
<dependency>
<groupId>org.crazycakegroupId>
<artifactId>shiro-redisartifactId>
<version>${shiro-redis.version}version>
<exclusions>
<exclusion>
<groupId>org.apache.shirogroupId>
<artifactId>shiro-coreartifactId>
exclusion>
exclusions>
dependency>
版本号:
<shiro-spring.version>1.4.0shiro-spring.version>
<shiro-redis.version>3.1.0shiro-redis.version>
2.shiro 配置类
package com.ym.auth.framework.config;
import com.ym.auth.common.utils.redis.RedisKeyUtil;
import com.ym.auth.framework.shiro.KickoutSessionControlFilter;
import com.ym.auth.framework.shiro.MySessionManager;
import com.ym.auth.framework.shiro.MyShiroRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
import javax.servlet.Filter;
import java.time.Duration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
*
*/
@Configuration
public class ShiroConfig {
@Resource
private RedisProperties redisProperties;
private Duration redisExpire = Duration.ofHours(1L);
public KickoutSessionControlFilter kickoutSessionFilter(){
KickoutSessionControlFilter kickoutSessionFilter = new KickoutSessionControlFilter();
//使用cacheManager获取相应的cache来缓存用户登录的会话;用于保存用户—会话之间的关系的;//这里我们还是用之前shiro使用的ehcache实现的cacheManager()缓存管理//也可以重新另写一个,重新配置缓存时间之类的自定义缓存属性//用于根据会话ID,获取会话进行踢出操作的;
kickoutSessionFilter.setCacheManager(myCacheManager());
kickoutSessionFilter.setSessionManager(sessionManager());
//是否踢出后来登录的,默认是false;即后者登录的用户踢出前者登录的用户;踢出顺序。
kickoutSessionFilter.setKickoutAfter(false);
//同一个用户最大的会话数,默认1;比如2的意思是同一个用户允许最多同时两个人登录;
kickoutSessionFilter.setMaxSession(5);
//被踢出后重定向到的地址;
kickoutSessionFilter.setKickoutUrl("/kickout");
return kickoutSessionFilter;
}
@Bean
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
//shiro 拦截配置
Map filters = shiroFilterFactoryBean.getFilters();
filters.put("kickoutSessionFilter",kickoutSessionFilter());
Map filterChainDefinitionMap = new LinkedHashMap();//注意过滤器配置顺序 不能颠倒//配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了,登出后跳转配置的loginUrl//后台首页密码找回时无需拦截登录过滤/sendCode /updatePassWord /checkCode
filterChainDefinitionMap.put("/logout", "logout");//配置不会被拦截的链接 顺序判断
filterChainDefinitionMap.put("/static/**", "anon");
filterChainDefinitionMap.put("/ajaxLogin", "anon");//开放swagger资源 start
filterChainDefinitionMap.put("/v2/api-docs", "anon");
filterChainDefinitionMap.put("/v2/api-docs-ext", "anon");
filterChainDefinitionMap.put("/doc.html", "anon");
filterChainDefinitionMap.put("/webjars/**", "anon");
filterChainDefinitionMap.put("/swagger-resources/**", "anon");
filterChainDefinitionMap.put("/swagger-ui.html", "anon");//配置shiro默认登录界面地址,前后端分离中登录界面跳转应由前端路由控制,后台仅返回json数据
shiroFilterFactoryBean.setLoginUrl("/unAuth");// 登录成功后要跳转的链接// shiroFilterFactoryBean.setSuccessUrl("/index");//未授权界面;// shiroFilterFactoryBean.setUnauthorizedUrl("/403");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);return shiroFilterFactoryBean;
}/**
* 凭证匹配器
* (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了
* )
*
* @return
*/@Beanpublic HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();//散列算法:这里使用MD5算法;
hashedCredentialsMatcher.setHashAlgorithmName(Sha256Hash.ALGORITHM_NAME);
hashedCredentialsMatcher.setStoredCredentialsHexEncoded(false);
hashedCredentialsMatcher.setHashIterations(1024);return hashedCredentialsMatcher;
}@Beanpublic MyShiroRealm myShiroRealm() {
MyShiroRealm myShiroRealm = new MyShiroRealm();
myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());return myShiroRealm;
}@Beanpublic MethodInvokingFactoryBean getMethodInvokingFactoryBean() {
MethodInvokingFactoryBean methodInvokingFactoryBean=new MethodInvokingFactoryBean();
methodInvokingFactoryBean.setStaticMethod("org.apache.shiro.SecurityUtils.setSecurityManager");
methodInvokingFactoryBean.setArguments(securityManager());return methodInvokingFactoryBean;
}@Beanpublic SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();// 自定义session管理 使用redis
securityManager.setSessionManager(sessionManager());// 自定义缓存实现 使用redis
securityManager.setCacheManager(myCacheManager());
securityManager.setRealm(myShiroRealm());return securityManager;
}//自定义sessionManager@Beanpublic SessionManager sessionManager() {
MySessionManager mySessionManager = new MySessionManager();
mySessionManager.setSessionDAO(redisSessionDAO());
mySessionManager.setDeleteInvalidSessions(true);//设置session过期时间为1小时(单位:毫秒),默认为30分钟
mySessionManager.setGlobalSessionTimeout(redisExpire.toMillis());
mySessionManager.setSessionIdCookie(simpleCookie());// 多久检测一次过期、无效的session.默认60分钟
mySessionManager.setSessionValidationSchedulerEnabled(true);//mySessionManager.setSessionValidationInterval(5000L);return mySessionManager;
}@Beanpublic SimpleCookie simpleCookie() {
SimpleCookie simpleCookie = new SimpleCookie("shiro.session.cookie");
simpleCookie.setPath("/");
simpleCookie.setHttpOnly(true);
simpleCookie.setSecure(true);//记住我有效期长达30天//simpleCookie.setMaxAge((int)redisExpire.toMillis());return simpleCookie;
}/**
* 配置shiro redisManager
*
* 使用的是shiro-redis开源插件
*
* @return
*/
public RedisManager redisManager() {
RedisManager redisManager = new RedisManager();
redisManager.setHost(redisProperties.getHost());
redisManager.setPort(redisProperties.getPort());
redisManager.setDatabase(redisProperties.getDatabase());
redisManager.setTimeout((int) redisProperties.getTimeout().toMillis());// redisManager.setPassword(redisProperties.getPassword());return redisManager;
}/**
* cacheManager 缓存 redis实现
*
* 使用的是shiro-redis开源插件
*
* @return
*/
@Beanpublic RedisCacheManager myCacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager());return redisCacheManager;
}/**
* RedisSessionDAO shiro sessionDao层的实现 通过redis
*
* 使用的是shiro-redis开源插件
*/
@Beanpublic RedisSessionDAO redisSessionDAO() {
RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
redisSessionDAO.setRedisManager(redisManager());
redisSessionDAO.setKeyPrefix("shiro:session");// redisSessionDAO.setExpire(1800);return redisSessionDAO;
}/**
* 开启shiro aop注解支持.
* 使用代理方式;所以需要开启代码支持;
*
* @param mySecurityManager
* @return
*/@Beanpublic AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager mySecurityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(mySecurityManager);return authorizationAttributeSourceAdvisor;
}@Beanpublic DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
advisorAutoProxyCreator.setProxyTargetClass(true);return advisorAutoProxyCreator;
}
}
2.session管理器MysessionMananger
package com.ym.auth.framework.shiro;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;
/**
* Created with IntelliJ IDEA.
* Description:
* Date: 2019-03-22
* Time: 12:00
* 自定义sessionId获取
*/
public class MySessionManager extends DefaultWebSessionManager{
private static final String AUTHORIZATION = "Authorization";
private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";
public MySessionManager() {
super();
}
@Override
protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
String id = WebUtils.toHttp(request).getHeader(AUTHORIZATION);
//如果请求头中有 Authorization 则其值为sessionId
if (!StringUtils.isEmpty(id)) {
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
return id;
} else {
//否则按默认规则从cookie取sessionId
return super.getSessionId(request, response);
}
}
}
3.ShiroRealm
package com.ym.auth.framework.shiro;@Override
4.登入人数踢出关键类
package com.ym.auth.framework.shiro;
import com.ym.auth.common.utils.redis.RedisKeyUtil;
import com.ym.auth.domain.entity.SysUser;
import lombok.Data;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;
import java.util.Deque;
import java.util.LinkedList;
/**
* @Author wenbo
* @Date 2020/4/15 16:26
**/
@Data
public class KickoutSessionControlFilter extends AccessControlFilter {
private static final Logger logger = LoggerFactory.getLogger(KickoutSessionControlFilter.class);
/** 踢出后到的地址 */
private String kickoutUrl;
/** 踢出之前登录的/之后登录的用户 默认踢出之前登录的用户 */
private boolean kickoutAfter = false;
/** 同一个帐号最大会话数 默认1 */
private int maxSession = 1;
private SessionManager sessionManager;
private Cache> cache;public void setCacheManager(CacheManager cacheManager) {this.cache = cacheManager.getCache(RedisKeyUtil.KEY_PREFIX+":shiro:session:auth:");
}/**
* 是否允许访问,返回true表示允许
*/@Overrideprotected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {return false;
}/**
* 表示访问拒绝时是否自己处理,
* 如果返回true表示自己不处理且继续拦截器链执行,
* 返回false表示自己已经处理了(比如重定向到另一个页面)。
*/@Overrideprotected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
Subject subject = getSubject(request, response);if(!subject.isAuthenticated()) {//如果没有登录,直接进行之后的流程return true;
}//这里获取的User是实体 因为我在 自定义ShiroRealm中的doGetAuthenticationInfo方法中//new SimpleAuthenticationInfo(user, password, getName());// 传的是 User实体 所以这里拿到的也是实体,如果传的是userName 这里拿到的就是userName
Session session = subject.getSession();
SysUser sysUser = (SysUser) subject.getPrincipal();
String name = sysUser.getCode();
Serializable sessionId = session.getId();//初始化用户的队列放到缓存里
Deque deque = cache.get(name);if(deque == null) {
deque = new LinkedList<>();
}//如果队列里没有此sessionId,且用户没有被踢出;放入队列if(!deque.contains(sessionId) && session.getAttribute("kickout") == null) {//将sessionId存入队列
deque.push(sessionId);// 将用户的sessionId队列缓存
cache.put(name, deque);
}//如果队列里的sessionId数超出最大会话数,开始踢人while(deque.size() > maxSession) {
logger.debug("===deque队列长度:==" + deque.size());
Serializable kickoutSessionId = null;//如果踢出后者if(kickoutAfter) {
kickoutSessionId = deque.removeFirst();
} else { //否则踢出前者
kickoutSessionId = deque.removeLast();
}//踢出后再更新下缓存队列
cache.put(name, deque);try {// 获取被踢出的sessionId的session对象
Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));if(kickoutSession != null) {//设置会话的kickout属性表示踢出了
kickoutSession.setAttribute("kickout", true);
}
} catch (Exception e) {//ignore exception
e.printStackTrace();
}
}//如果被踢出了,直接退出,重定向到踢出后的地址if (session.getAttribute("kickout") != null
&& (Boolean) session.getAttribute("kickout")) {//会话被踢出了try {
subject.logout();
} catch (Exception e) {
logger.info("shiro 踢出退出登录异常{}",e.getCause());
}
WebUtils.issueRedirect(request, response, kickoutUrl);return false;
}return true;
}
}
5.登陆Controller
@Api(tags = "登录")
@Controller
@Validated
public class LoginController extends BaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);
@Log
@ApiOperation("用户登录")
@PostMapping(value = "/ajaxLogin", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public APIResponse submitLogin(
@ApiParam(name = "loginVo", value = "账号", required = true)
@Validated(PCLoginVo.Login.class) @RequestBody PCLoginVo loginVo) {
Subject subject = SecurityUtils.getSubject();
String code = loginVo.getCode();
UsernamePasswordToken token = new UsernamePasswordToken(code, loginVo.getPwd());
try {
subject.login(token);
} catch (IncorrectCredentialsException e) {
return failMsg("密码错误");
} catch (DisabledAccountException e) {
return failMsg("登录失败,该用户已被禁用");
} catch (AuthenticationException e) {
return failMsg("该用户不存在");
} catch (Exception e) {
LOGGER.error("find exception:e={}", e);
return failMsg("未知系统异常");
}
session.setAttribute(Global.APP_KEY,sign.getAppKey());
Map map = new LinkedHashMap<>(6); //返回登录成功后的数据
map.put("user","")return successData(map);
}/**
* 退出登录
*
* @return
*/@ApiOperation("退出登录")@GetMapping("/logOut")@ResponseBodypublic APIResponse logOut() {
Subject subject = SecurityUtils.getSubject();
subject.logout();return successMsg("退出成功");/**
* 未登录,shiro应重定向到登录界面,此处返回未登录状态信息由前端控制跳转页面
*
* @return
*/@GetMapping(value = "/unAuth")@ResponseBodypublic APIResponse unAuth() {return failData(ResultCode.NO_LOGIN);
}/**
* 踢出登录时返回信息
* USER_LOGGING_IN_MULTIPLE_PLACES(1000005, "用户在多地登录"),
*
* @return
*/@GetMapping(value = "/kickout")@ResponseBodypublic APIResponse kickout() {return failData(ResultCode.USER_LOGGING_IN_MULTIPLE_PLACES);
}
更多精彩:
Fork/Join 一定快吗?
JDK 代理以及Cglib 代理
Delayed 延时队列
大型分布式系统高性能并发编程系列之线程异步并返回结果(22)
长按关注我
喜欢就点个在看