Shiro是什么?
Spring security 重量级安全框架
Apache shiro 轻量级安全框架
Shiro是一个强大且易用的Java权限框架
四大基石
身份验证,授权,密码学,会话管理
/** * String algorithmName, Object source, Object salt, int hashIterations) * 第一个参数algorithmName:加密算法名称 * 第二个参数source:加密原密码 * 第三个参数salt:盐值 * 第四个参数hashIterations:加密次数 */ SimpleHash hash = new SimpleHash("MD5","123456","itsource",10); System.out.println(hash.toHex());
4.自定义Realm
继承AuthorizingRealm
实现两个方法:doGetAuthorizationInfo(授权) /doGetAuthenticationInfo(登录认证)
//身份认证@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { //1.拿用户名与密码 UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken; String username = token.getUsername(); //2.根据用户名拿对应的密码 String password = getByName(username); if(password==null){ return null; //返回空代表用户名有问题 } //返回认证信息 //准备盐值 ByteSource salt = ByteSource.Util.bytes("itsource"); //密码是shiro自己进行判断 SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username,password,salt,getName()); return authenticationInfo; }
//授权@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { //拿到用户名 Principal:主体(用户对象/用户名) String username = (String)principalCollection.getPrimaryPrincipal(); //拿到角色 Setroles = findRolesBy(username); //拿到权限 Set permis = findPermsBy(username); //把角色权限交给用户 SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); authorizationInfo.setRoles(roles); authorizationInfo.setStringPermissions(permis); return authorizationInfo; }
注意:如果我们的密码加密,应该怎么判断(匹配器)
//一.创建我们自己的RealmMyRealm myRealm = new MyRealm(); //创建一个凭证匹配器(无法设置盐值) HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(); // 使用MD5的方式比较密码 matcher.setHashAlgorithmName("md5"); // 设置编码的迭代次数 matcher.setHashIterations(10); //设置凭证匹配器(加密方式匹配) myRealm.setCredentialsMatcher(matcher);
5.集成Spring
去找:shiro-root-1.4.0-RC2\samples\spring
5.1 导包
org.apache.shiro shiro-all 1.4.0 pom org.apache.shiro shiro-spring 1.4.0
5.2 web.xml
这个过滤器是一个代码(只关注它的名称)
shiroFilter org.springframework.web.filter.DelegatingFilterProxy targetFilterLifecycle true shiroFilter /*
5.3 application-shiro.xml
在咱们的application引入
<import resource="classpath:applicationContext-shiro.xml" />
是从案例中拷备过来,进行了相应的修改
5.4 获取Map过滤
注意,返回的Map必需是有序的(LinkedHashMap)
public class FilterChainDefinitionMapFactory { /** * 后面这个值会从数据库中来拿 * /s/login.jsp = anon * /login = anon * /s/permission.jsp = perms[user:index] * /depts/index = perms[depts:index] * /** = authc */ public MapcreateFilterChainDefinitionMap(){ //注:LinkedHashMap是有序的 Map filterChainDefinitionMap = new LinkedHashMap<>(); filterChainDefinitionMap.put("/s/login.jsp", "anon"); filterChainDefinitionMap.put("/login", "anon"); filterChainDefinitionMap.put("/s/permission.jsp", "perms[user:index]"); filterChainDefinitionMap.put("/depts/index", "perms[depts:index]"); filterChainDefinitionMap.put("/**", "authc"); return filterChainDefinitionMap; } }