SSM集成安全框架shiro
前言,阅读这篇博客前可以先看看RBAC打造通用的权限管理平台http://blog.youkuaiyun.com/sinat_15153911/article/details/55046741
之前小编一直用拦截器来实现权限登录的拦截,现在使用高大上的shiro,多重拦截,大量拦截,其中一个安全知识点是md5颜值加密,噢,是盐值。现在就一步一步教大家怎么配置。
也可以加Q490647751,回复‘开通VIP获取SSM集成安全框架shiro’,获取源码研究,当然你还可以使用shiro二级缓存ehcache或者redis缓存session。
视频教程:链接:http://pan.baidu.com/s/1geQJCH1 密码:mo22
第一步导入jar包
shir-core-1.2.3.jar
shiro-ehcache-1.2.3.jar
shiro-spring-1.2.3.jar
shiro-web-1.2.3.jar
第二步配置web.xml
<!-- shiro的filter -->
<!-- shiro过虑器,DelegatingFilterProxy通过代理模式将spring容器中的bean和filter关联起来 -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>shiroFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
第三步加配置文件applicationContext-shiro.xml
<import resource="applicationContext-*.xml"/>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- web.xml中shiro的filter对应的bean -->
<!-- Shiro 的Web过滤器 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<!-- loginUrl认证提交地址,如果没有认证将会请求此地址进行认证,请求此地址将由formAuthenticationFilter进行表单认证 -->
<property name="loginUrl" value="/manage/login.html" />
<!-- 认证成功统一跳转到index.html,建议不配置,shiro认证成功自动到上一个请求路径 -->
<property name="successUrl" value="/manage/index.html"/>
<!-- 通过unauthorizedUrl指定没有权限操作时跳转页面-->
<property name="unauthorizedUrl" value="/manage/refuse.html" />
<!-- 自定义filter配置 -->
<!-- <property name="filters">
<map>
将自定义 的FormAuthenticationFilter注入shiroFilter中
<entry key="authc" value-ref="formAuthenticationFilter" />
</map>
</property> -->
<!-- 过虑器链定义,从上向下顺序执行,一般将/**放在最下边 -->
<property name="filterChainDefinitions">
<value>
<!-- 对静态资源设置匿名访问 -->
/resource/** = anon
/file/** = anon
<!-- 验证码,可匿名访问 -->
/validatecode.jsp = anon
<!-- 请求 logout.action地址,shiro去清除session-->
/logout.html = logout
<!--商品查询需要商品查询权限 ,取消url拦截配置,使用注解授权方式 -->
<!-- /items/queryItems.action = perms[item:query]
/items/editItems.action = perms[item:edit] -->
<!-- 配置记住我或认证通过可以访问的地址 -->
/login.jsp = user
/index.html = user
/welcome.jsp = user
<!-- /** = authc 所有url都必须认证通过才可以访问-->
/** = authc
<!-- /** = anon所有url都可以匿名访问 -->
</value>
</property>
</bean>
<!-- securityManager安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="customRealm" />
<!-- 注入缓存管理器 -->
<!-- <property name="cacheManager" ref="cacheManager"/> -->
<!-- 注入session管理器 -->
<property name="sessionManager" ref="sessionManager" />
<!-- 记住我 -->
<property name="rememberMeManager" ref="rememberMeManager"/>
</bean>
<!-- realm -->
<bean id="customRealm" class="com.yanhui.shiro.CustomRealm">
<!-- 将凭证匹配器设置到realm中,realm按照凭证匹配器的要求进行散列 -->
<property name="credentialsMatcher" ref="credentialsMatcher"/>
</bean>
<!-- 凭证匹配器 -->
<bean id="credentialsMatcher"
class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="md5" />
<property name="hashIterations" value="1" />
</bean>
<!-- 缓存管理器 -->
<!-- <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml"/>
</bean> -->
<!-- 会话管理器 -->
<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<!-- session的失效时长,单位毫秒 -->
<property name="globalSessionTimeout" value="600000"/>
<!-- 删除失效的session -->
<property name="deleteInvalidSessions" value="true"/>
</bean>
<!-- rememberMeManager管理器 -->
<bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
<property name="cookie" ref="rememberMeCookie" />
</bean>
<!-- 记住我cookie -->
<bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<constructor-arg value="rememberMe" />
<!-- 记住我cookie生效时间30天 -->
<property name="maxAge" value="2592000" />
</bean>
</beans>
第四步添加CustomRealm的类
package com.yanhui.shiro;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import com.yanhui.mapping.system.UserManagerMapper;
import com.yanhui.pojo.auth.Permission;
import com.yanhui.pojo.system.UserManager;
import com.yanhui.service.auth.PermissionService;
public class CustomRealm extends AuthorizingRealm {
public static void main(String[] args) {
//所需加密的参数 即 密码
String source = "123456";
//[盐] 一般为用户名 或 随机数
String salt = "customRealm";
//加密次数
int hashIterations = 1;
//调用 org.apache.shiro.crypto.hash.Md5Hash.Md5Hash(Object source, Object salt, int hashIterations)构造方法实现MD5盐值加密
Md5Hash mh = new Md5Hash(source, salt, hashIterations);
//打印最终结果
System.out.println(mh.toString());
/*调用org.apache.shiro.crypto.hash.SimpleHash.SimpleHash(String algorithmName, Object source, Object salt, int hashIterations)
* 构造方法实现盐值加密 String algorithmName 为加密算法 支持md5 base64 等*/
SimpleHash sh = new SimpleHash("md5", source, salt, hashIterations);
//打印最终结果
System.out.println(sh.toString());
}
@Autowired
private UserManagerMapper userMapper;
@Autowired
private PermissionService permissionService;
@Override
public String getName() {
return "customRealm";
}
// 支持什么类型的token
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof UsernamePasswordToken;
}
// 认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
// 从token中 获取用户身份信息
String username = (String) token.getPrincipal();
// 拿username从数据库中查询
// UserExample example = new UserExample();
// Criteria criteria = example.createCriteria();
// criteria.andNameEqualTo(username);
Map<String,Object> map = new HashMap<String,Object>();
map.put("name", username);
List<UserManager> list = userMapper.listForPage(map);
if(list.size() < 1){
// 如果查询不到则返回null
return null;
}
UserManager user = list.get(0);
// 获取从数据库查询出来的用户密码
String password = user.getPassword();
// String salt = user.getSalt();
// String password = "cb571f7bd7a6f73ab004a70322b963d5";
String salt = "customRealm";
// 如果查询到返回认证信息AuthenticationInfo
//activeUser就是用户身份信息
UserManager activeUser = new UserManager();
activeUser.setId(user.getId());
// activeUser.setUsercode(user.getPhone());
activeUser.setUsername(user.getUsername());
// 返回认证信息由父类AuthenticatingRealm进行认证
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
// employee.getPhone(), "123456", ByteSource.Util.bytes(salt), this.getName());
user, password, ByteSource.Util.bytes(salt), getName());
return simpleAuthenticationInfo;
}
// 授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals) {
//身份信息
UserManager activeUser = (UserManager) principals.getPrimaryPrincipal();
// Employee activeUser = (Employee) subject.getPrincipal();
//用户id
Integer userid = activeUser.getId();
//获取用户权限
List<Permission> permissions = null;
try {
permissions = permissionService.findPermissionList(userid);
} catch (Exception e) {
e.printStackTrace();
}
//构建shiro授权信息
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
for(Permission permission : permissions){
simpleAuthorizationInfo.addStringPermission(permission.getPercode());
}
return simpleAuthorizationInfo;
}
//清除缓存
public void clearCached() {
PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
super.clearCache(principals);
}
}
第五步登录方法
/**
* 后台管理主页
* @return
*/
@RequestMapping("/index")
public String indexAdmin(HttpServletRequest request){
//主体
Subject subject = SecurityUtils.getSubject();
// //身份
UserManager activeUser = (UserManager) subject.getPrincipal();
request.setAttribute("activeUser", activeUser);
HttpSession session = request.getSession();
session.setAttribute(Global.USER_BACKEND_SESSION, activeUser);
request.setAttribute("mainPage", "welcome.html");
return Global.WEB_BACK_PAGE + "/index";
}
/**
* 后台登录
* @return
* @throws Exception
*/
@RequestMapping("/login")
public String login(String username,String password,HttpServletRequest request) throws Exception{
//如果登陆失败从request中获取认证异常信息,shiroLoginFailure就是shiro异常类的全限定名
String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
//根据shiro返回的异常类路径判断,抛出指定异常信息
if(exceptionClassName!=null){
if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
//最终会抛给异常处理器
//throw new CustomException("账号不存在");
System.out.println("账号不存在");
} else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
//throw new CustomException("用户名/密码错误");
System.out.println("用户名/密码错误");
} /*else if("randomCodeError".equals(exceptionClassName)){
//throw new CustomException("验证码错误 ");
}*/else {
System.out.println("未知错误");
throw new Exception();//最终在异常处理器生成未知错误
}
}
// String result = "";
// UserManager user = userService.login(username,password);
// if(user != null){
// HttpSession session = request.getSession();
// session.setAttribute(Global.USER_BACKEND_SESSION, user);
// result = "redirect:/manage/index.html";
// }else{
// result = "redirect:/manage/toSignIn.html";
// }
// return result;
return Global.WEB_BACK_PAGE + "/signin";
}
第六步前端显示
<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>
<shiro:hasPermission name="dic:query">
<a href="http://www.baidu.com" class="list-title">dic列表</a>
</shiro:hasPermission>
知识点:
1、自定义Realm
自定义Realm一般需要实现AuthorizingRealm接口,该接口有两个接口,一个是doGetAuthorizationInfo,另一个是doGetAuthenticationInfo。
doGetAuthenticationInfo(认证)
该接口方法的逻辑是验证用户登录的合法性,通常在这里面来判断用户名是否存在、密码是否正确、用户账号状态是否被禁用或者锁定等操作。
doGetAuthorizationInfo(授权)
该接口方法的逻辑是在用户身份验证完成后,设置用户的权限信息,一般包括设置用户所拥有的角色信息和相应的权限字信息。
2、MD5盐值加密
int temp;
temp = ss < 0 ? ss + 256 : ss;
return GOAL[temp / 16] + GOAL[temp % 16]; //自己实现转化
/*
用现有的方法实现转化
StringBuffer s = new StringBuffer();
if(temp < 16)s.append("0");
s.append(Integer.toHexString(temp));
return s.toString();
*/
String password_md5_sale_1 = new Md5Hash("123456", "customRealm", 1).toString();
<!-- 凭证匹配器 -->
<bean id="credentialsMatcher"
class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="md5" />
<property name="hashIterations" value="1" />
</bean>