公司的公共服务-通知中心要添加登录验权功能,在考虑到以后的扩展性和集群部署的特性,选择了shiro+redis 的方案,现在就跟随我看看一个适用于集群的shiro是如何搭建的。
shiro配置
导包
修改web.xml
添加shiro-spring.xml 文件
shiro相关代码
自定义Realm
RedisCache实现
Start
配置
导入shiro相关jar包,这里使用maven来管理
image.png
修改原有的web.xml文件,shiro接管Servlet过滤器
image.png
3.工程使用的是spring,这里添加shiro-spirng.xml 完成shiro核心功能的配置和依赖。
在原有application.xml 文件中添加(文件名自定义)
创建shiro-spring.xml 文件(我这里命名为security-context)
添加凭证匹配器(密码使用MD5加密验证,散列次数=1)
class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
添加自定义realm(安全数据源),并开启缓存和注入凭证匹配器
RedisCache相关类注册,这里使用了Git开源的shiro+redis缓存实现(https://github.com/alexxiyang/shiro-redis),做了本地化改造
class="com.lingyun.security.rediscache.ShardedJedisPoolManager">
添加SimpleCookie,修改默认sessionID。默认sessionID 为JSESSIONID 会和容器名冲突, 如JETTY, TOMCAT 等,导致session失效
添加会话管理器,
配置shiroWeb过滤器,实现url自定义拦截
/static/** = anon
/doLogin = anon
/error = anon
/send* = anon
/** = user
开启rememberMe功能
最后注册安全管理器,注入相关管理器
到这里shiro相关的配置及改造就结束了,接下来是一些和业务绑定的代码和数据库相关
continue
代码编写及改造
创建用户DTO和Table,这里要注意UserDTO一定要实现序列化接口,redis缓存时会序列化对象
image.png
2.自定义Realm实现,要注意因为使用了凭证匹配器,认证时不用再做密码验证,将数据源中的密码传入即可,另外因实现了redis缓存,要传入UserDTO实例
/**
* 认证
*
* @param token
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String) token.getPrincipal();
NoticeUserDTO user = noticeUserInfoService.findUserIFByName(username);
if (user == null || user.getDataState() == 0) {
throw new UnknownAccountException(); //用户为空
}
//如果身份认证验证成功,返回一个AuthenticationInfo实现;
return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
}
这样一个简版的shiro框架就搭建起来了,至于权限验证和其他功能,在以后的工作再慢慢添加。
终