基于spring的shiro配置

来源:互联网 发布:oppo手机照片导入mac 编辑:程序博客网 时间:2024/05/10 21:57

Shiro继承spring

1.需要所有的springmvc.xml的配置

2.需要所有的web.xml的配置

3.需要所有的pom.xml的依赖

4.需要所有的spring.xml的配置

5.jdbc.properties文件

 

Web.xml配置

[html] view plain copy
  1. <!-- 配置shiro的代理过滤器   filter-name的名字和spring中bean的id一样 -->  
  2. <filter>  
  3.     <filter-name>shiroFilter</filter-name>  
  4.     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
  5.     <init-param>  
  6.         <param-name>targetFilterLifecycle</param-name>  
  7.         <param-value>true</param-value>  
  8.     </init-param>  
  9. </filter>  
  10. <filter-mapping>  
  11.     <filter-name>shiroFilter</filter-name>  
  12.     <url-pattern>/*</url-pattern>  
  13. </filter-mapping>  


 

spring.xml中配置realm

[html] view plain copy
  1. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
  2. lt;!-- ref="myDbRealm" 自定义类MyDbRealm加注解@component继承AuthorizingRealm -->  
  3.    <property name="realm" ref="myDbRealm"/>  
  4. lt;/bean>  
  5. <!-- 后置处理器(用来注销securityManager) -->  
  6. lt;bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>  


spring.xml中配置ini

 

[html] view plain copy
  1. <!-- spring 配置ini  bean的id与web.xml中filter-name一样-->  
  2.  <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
  3.     <property name="securityManager" ref="securityManager"/>  
  4.     <property name="loginUrl" value="/login.html"/>  
  5.     <property name="unauthorizedUrl" value="/un.html"/>  
  6.       
  7.     <property name="filterChainDefinitions">  
  8.         <value>  
  9.             /login.html = anon  
  10. /scu.jsp = authc  
  11.         </value>  
  12.     </property>  
  13. </bean>  

加入依赖:

[html] view plain copy
  1. 1. <dependency>    
  2. 2.     <groupId>org.apache.shiro</groupId>    
  3. 3.     <artifactId>shiro-spring</artifactId>    
  4. 4.     <version>1.4.0</version>    
  5. 5. </dependency>  

  

自定义filter实现动态配置url拦截

[html] view plain copy
  1. package cn.et.shiro.conf;  
  2.    
  3. import java.util.List;  
  4. import java.util.Set;  
  5. import java.util.regex.Pattern;  
  6.    
  7. import javax.servlet.ServletRequest;  
  8. import javax.servlet.ServletResponse;  
  9. import javax.servlet.http.HttpServletRequest;  
  10.    
  11. import org.apache.shiro.spring.web.ShiroFilterFactoryBean;  
  12. import org.apache.shiro.subject.Subject;  
  13. import org.apache.shiro.util.CollectionUtils;  
  14. import org.apache.shiro.web.filter.authz.AuthorizationFilter;  
  15. import org.springframework.beans.factory.annotation.Autowired;  
  16. import org.springframework.stereotype.Component;  
  17.    
  18. import cn.et.shiro.dao.UserMapper;  
  19. import cn.et.shiro.entity.Menu;  
  20.    
  21. @Component    
  22. public class MyFilter extends AuthorizationFilter {    
  23.         
  24.     @Autowired    
  25.     private ShiroFilterFactoryBean sffb;    
  26.     /**    
  27.      * 匹配指定过滤器规则的url    
  28.      * @param regex    
  29.      * @param url    
  30.      * @return    
  31.      */    
  32.     public static boolean matchUrl(String regex,String url){    
  33.          
  34.         regex=regex.replaceAll("/+", "/");    
  35.         if(regex.equals(url)){    
  36.             return true;    
  37.         }    
  38.         regex=regex.replaceAll("\\.", "\\\\.");    
  39.         // /login.html  /l*.html    
  40.         regex=regex.replaceAll("\\*", ".*");    
  41.         // /**/login.html  /a/b/login.html    
  42.         if(regex.indexOf("/.*.*/")>=0){    
  43.             regex=regex.replaceAll("/\\.\\*\\.\\*/", "((/.*/)+|/)");    
  44.         }    
  45.         System.out.println(regex+"----"+url);    
  46.         return Pattern.matches(regex, url);    
  47.     }    
  48.     @Autowired  
  49.     UserMapper userMapper;  
  50.     /**    
  51.      * 测试    
  52.      * @param args    
  53.      */    
  54.     public static void main(String[] args) {    
  55.         System.out.println(matchUrl("/**/s*.html","/t/g/login.html"));    
  56.     }      
  57.       
  58.     /**    
  59.      * isAccessAllowed用于判断当前url的请求是否能验证通过  如果验证失败 调用父类的onAccessDenied决定跳转到登录失败页还是授权失败页面    
  60.      */    
  61.     @Override    
  62.     protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)    
  63.             throws Exception {  
  64.       
  65.         HttpServletRequest req=(HttpServletRequest)request;    
  66.         String contextPath=req.getContextPath();  
  67.         //获取用户访问的资源的路径  
  68.         String url=req.getRequestURI();  
  69.         url=url.split(contextPath)[1];  
  70.         //获取哪些url需要哪些认证  
  71.         //List<Menu> queryMenu=userMapper.queryMenuByUrl(url);  
  72.         List<Menu> queryMenu=userMapper.qieryMenu();  
  73.         if(queryMenu.size()==0){  
  74.             return false;  
  75.         }  
  76.         String urlAuth=null;  
  77.         for(Menu menu:queryMenu){  
  78.             if(matchUrl(menu.getMenuUrl(),url)){  
  79.             //取出权限  
  80.             urlAuth=menu.getMenuFilter();  
  81.             }  
  82.         }  
  83.         //通数据库没有配置当前url的授权  
  84.          
  85.          
  86.         if(urlAuth==null){    
  87.             return false;    
  88.         }    
  89.         //配置的过滤器是anon 直接放过    
  90.         if(urlAuth.startsWith("anon")){    
  91.             return true;    
  92.         }    
  93.         //配置的是authc 判断当前用户是否认证通过    
  94.         Subject subject = getSubject(request, response);    
  95.         if(urlAuth.startsWith("authc")){    
  96.             return subject.isAuthenticated();    
  97.         }    
  98.         //授权认证 也需要判断是否登录 没有登录返回 登录继续下面的验证    
  99.         boolean ifAuthc=subject.isAuthenticated();    
  100.         if(!ifAuthc)    
  101.             return ifAuthc;    
  102.         //如果是定义的roles过滤器  获取所有的roles 一般是roles[a,b]    
  103.         if(urlAuth.startsWith("roles")){    
  104.             String[] rolesArray=urlAuth.split("roles\\[")[1].split("\\]")[0].split(",");    
  105.             if (rolesArray == null || rolesArray.length == 0) {    
  106.                 return true;    
  107.             }    
  108.             Set<String> roles = CollectionUtils.asSet(rolesArray);    
  109.             return subject.hasAllRoles(roles);    
  110.         }    
  111.         if(urlAuth.startsWith("perms")){    
  112.             String[] perms=urlAuth.split("perms\\[")[1].split("\\]")[0].split(",");    
  113.             boolean isPermitted = true;    
  114.             if (perms != null && perms.length > 0) {    
  115.                 if (perms.length == 1) {    
  116.                     if (!subject.isPermitted(perms[0])) {    
  117.                         isPermitted = false;    
  118.                     }    
  119.                 } else {    
  120.                     if (!subject.isPermittedAll(perms)) {    
  121.                         isPermitted = false;    
  122.                     }    
  123.                 }    
  124.             }    
  125.     
  126.             return isPermitted;    
  127.         }    
  128.         return false;    
  129.     }    
  130.     
  131. }  


 

认证登录实现AuthorizingRealm 

[html] view plain copy
  1. package cn.et.shiro.conf;  
  2.    
  3. import java.util.Set;  
  4.    
  5. import org.apache.shiro.authc.AuthenticationException;  
  6. import org.apache.shiro.authc.AuthenticationInfo;  
  7. import org.apache.shiro.authc.AuthenticationToken;  
  8. import org.apache.shiro.authc.SimpleAccount;  
  9. import org.apache.shiro.authc.UsernamePasswordToken;  
  10. import org.apache.shiro.authz.AuthorizationInfo;  
  11. import org.apache.shiro.authz.SimpleAuthorizationInfo;  
  12. import org.apache.shiro.realm.AuthorizingRealm;  
  13. import org.apache.shiro.subject.PrincipalCollection;  
  14. import org.springframework.beans.factory.annotation.Autowired;  
  15. import org.springframework.stereotype.Component;  
  16.    
  17. import cn.et.shiro.dao.UserMapper;  
  18. import cn.et.shiro.entity.UserInfo;  
  19. @Component  
  20. public class MyDbRealm extends AuthorizingRealm {  
  21. @Autowired  
  22. UserMapper userMapper;  
  23. /**  
  24.  * 认证  
  25.  * 将登陆输入的用户名和密码和数据库中的用户名和密码对比  是否相等  
  26.  * 返回值null表示认证失败 非null认证通过  
  27.  */  
  28. @Override  
  29. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {  
  30. //获取从页面传入的token  
  31. UsernamePasswordToken upt=(UsernamePasswordToken)token;  
  32. //从数据库中查询userinfo对象  
  33. UserInfo queryUser=userMapper.queryUser(upt.getUsername());  
  34. //如果对象不为空,且密码相等 可以登录  
  35. if(queryUser!=null && queryUser.getPassword().equals(new String(upt.getPassword()))){  
  36. SimpleAccount sa=new SimpleAccount(upt.getUsername(),upt.getPassword(),"MyDbRealm");  
  37. return sa;  
  38. }  
  39. return null;  
  40. }  
  41. /**  
  42.  * 获取当前文件的授权数据  
  43.  * 将当前用户在数据库的角色和权限 加载到AuthorizationInfo  
  44.  * 默认在进行授权认证的调用 检查权限调用checkRole checkPerm  
  45.  */  
  46. @Override  
  47. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {  
  48. //获取用户名  
  49. String userName=principals.getPrimaryPrincipal().toString();  
  50. //获取角色  
  51. Set<String> roleList=userMapper.queryRoleByName(userName);  
  52. //获取权限  
  53. Set<String> permsList=userMapper.queryPermsByName(userName);  
  54. SimpleAuthorizationInfo sa=new SimpleAuthorizationInfo();  
  55. sa.setRoles(roleList);  
  56. sa.setStringPermissions(permsList);  
  57. return sa;  
  58. }  
  59. }  
  60.    
阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 blued下载不了怎么办 文件格式错误怎么办 错误码2611003怎么办 优惠券被天猫吞了怎么办 鞋子放鞋盒发霉怎么办 蘑菇街登不上怎么办 桑蚕丝衣服皱褶怎么办 羊毛衫会扎人怎么办 肌肉腿外翻怎么办 大腿赘肉怎么办 淘宝卖家不举证怎么办 咸鱼收到假货怎么办 伤没钱看病怎么办 steam付款失败怎么办 配偶没有公积金怎么办 玩吃鸡配置不够怎么办 华为AL20黑屏怎么办 华为照片不见了怎么办 电话卡暂停服务怎么办 电脑屏幕居中了怎么办 冰箱霜太多怎么办 qq账号忘了怎么办没有邮箱怎么办 车祸赔不起怎么办对方天天闹怎么办 专家解读有口臭怎么办口气重怎么办 油锅起火时应该怎么办或者怎么办 淘宝买了东西想改地址怎么办怎么办 手机显示程序异常这是怎么办怎么办 钢笔笔尖坏了怎么办 陶瓷刀钝了怎么办 地下城fps低怎么办 床头只能朝西怎么办 钢笔笔尖歪了怎么办 钢笔笔尖漏墨怎么办 被蜈蚣咬了怎么办 信用卡被盗刷了怎么办 练太极拳膝盖痛怎么办 僵尸毛毛虫咬了怎么办 迅雷下载速度慢怎么办 驾驶证换证过期怎么办 发生地震时该怎么办 尿常规潜血十3怎么办