shiro框架的权限控制(Spring整合)

一.shrio简介
     Apache Shiro 是一个强大而灵活的开源安全框架,它干净利落地处理身份认证,授权,企业会话管理和加密。 
shiro主要能做的事:
1. 验证用户来核实他们的身份 
2. 对用户执行访问控制, 如:  判断用户是否被分配了一个确定的安全角色  判断用户是否被允许做某事 
3. 在任何环境下使用 Session API,即使没有 Web 或 EJB 容器。 
4. 在身份验证,访问控制期间或在会话的生命周期,对事件作出反应。
5. 聚集一个或多个用户安全数据的数据源,并作为一个单一的复合用户“视图”。
6. 启用单点登录(SSO)功能。 
7. 为没有关联到登录的用户启用"Remember Me"服务
二.Shiro 的架构的3 个主要概念:Subject,SecurityManager 和 Realms
    Subject:简单理解为当前登录的用户或者正在与应用程序交互的东西
    SecurityManager:整个shiro框架的核心,用来管理协调繁重的操作,包括认证,授权,与数据库交互,session管理,缓存管理等等
    Realms::Realms 担当 Shiro 和应用程序的安全数据之间的“桥梁”或“连接器,开发人员通常需要编写自己的realm类来进行自己的认证与授权,通常需要与数据库交互.
三.Shiro与Spring的整合使用
1.在web.xml中配置shrioFilter拦截器  
   
   
  1. <filter> 
          <filter-name>ShiroFilter</filter-name>            <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>        </filter>   
  1.  <filter-mapping>
  2.     <filter-name>ShiroFilter</filter-name>
  3.     <url-pattern>*/</url-pattern>
  4.  </filter-mapping> 

2.创建自己的MyRealm类
   
   
  1. public class MyRealm extends AuthorizingRealm {
  2. @Resource
  3. private IUserDao iUserDaoImpl;
  4. @Override
  5. protected AuthenticationInfo doGetAuthenticationInfo(
  6. AuthenticationToken token) throws AuthenticationException {
  7. // 用户登录的认证
  8. UsernamePasswordToken atoken = (UsernamePasswordToken) token;
  9. String username = atoken.getUsername();
  10. User user = iUserDaoImpl.findByUsername(username);
  11. if (user == null) {
  12. return null;
  13. } else {
  14. SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,
  15. user.getPassword(), this.getClass().getName());
  16. return info;
  17. }
  18. }
  19. @Override
  20. protected AuthorizationInfo doGetAuthorizationInfo(
  21. PrincipalCollection principal) {
  22. //用户授权
  23. SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
  24. User user = (User) principal.getPrimaryPrincipal();
  25. List<AuthFunction> list =null;
  26. if(user.getUsername().equals("admin")){
  27. //查出所有权限
  28. list= iUserDaoImpl.findAllFunctions();
  29. }else {
  30. //根据用户id查出对应权限
  31. list = iUserDaoImpl.findFunctionsById(user.getId());
  32. }
  33. // 授权
  34. if(list!=null){
  35. for (AuthFunction authFunction : list) {
  36. info.addStringPermission(authFunction.getCode());
  37. }
  38. }
  39. return info;
  40. }
  41. }
2.配置Spring
   
   
  1. <!-- shrio开发bean配置 -->
  2. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  3. <property name="securityManager" ref="securityManager" />
  4. <property name="loginUrl" value="/login.jsp" />
  5. <property name="successUrl" value="/home.jsp" />
  6. <property name="unauthorizedUrl" value="/unauthorized.jsp" />
  7. <property name="filterChainDefinitions">
  8. <value>
  9. /css/**=anon
  10. /images/**=anon
  11. /js/**=anon
  12. /validatecode.jsp=anon
  13. /login.jsp=anon
  14. /userAction_login.action=anon
  15. /page_base_staff.action=perms["staff"]
  16. /**=anon
  17. </value>
  18. </property>
  19. </bean>
  20. <!-- shiro安全管理器 -->
  21. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
  22. <property name="realm" ref="myRealm"></property>
  23. <property name="cacheManager" ref="cacheManager"></property>
  24. </bean>
  25. <bean id="myRealm" class="com.wuhan.bos.shiro.MyRealm" />
  26. <bean id ="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
  27. <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"></property>
  28. </bean>
  29. <!-- shiro注解开发,cglib动态代理 -->
  30. <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator">
  31. <property name="proxyTargetClass" value="true"></property>
  32. </bean>
  33. <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
  34. </bean>
4.提供 ehcache 缓存策略的配置文件ehcache.xml
   
   
  1. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
  2. <diskStore path="java.io.tmpdir"/>
  3. <defaultCache
  4. maxElementsInMemory="10000"
  5. eternal="false"
  6. timeToIdleSeconds="120"
  7. timeToLiveSeconds="120"
  8. overflowToDisk="true"
  9. maxElementsOnDisk="10000000"
  10. diskPersistent="false"
  11. diskExpiryThreadIntervalSeconds="120"
  12. memoryStoreEvictionPolicy="LRU"
  13. />
  14. </ehcache>
四.shiro的注解开发
       shiro框架整合到Spring后,可以使用注解开发,即通过在资源上提供注解来控制用户的访问权限,提高权限控制的细度,可以和配置文件结合使用
常见的主要有以下几种:
@RequiresAuthentication:验证用户是否登录,等同于方法subject.isAuthenticated() 结果为true时,即登录后可访问
@ RequiresUser:验证用户是否被记忆,user有两种含义: 一种是成功登录的(subject.isAuthenticated() 结果为                                                 true); 另外一种是被记忆的( subject.isRemembered()结果为true)。
@ RequiresGuest:验证是否是一个guest(游客)的请求,与@ RequiresUser完全相反。  换言之,RequiresUser  ==                                                              !RequiresGuest 。 此时subject.getPrincipal() 结果为null.
@ RequiresRoles
例如:@RequiresRoles("aRoleName");
void someMethod();
如果subject中有aRoleName角色才可以访问方法someMethod。如果没有这个权限则会抛出异常AuthorizationException。
@RequiresPermissions
例如: @RequiresPermissions( {"file:read", "write:aFile.txt"} )
           void someMethod();
要求subject中必须同时含有file:read和write:aFile.txt的权限才能执行方法someMethod()。否则抛出异常AuthorizationException。
五.shiro框架提供的标签
标签名称                                                             标签条件(均是显示标签内容)
<shiro:authenticated>                                                        登录之后
<shiro:notAuthenticated>                                              不在登录状态时
<shiro:guest>                                                              用户在没有RememberMe时
<shiro:user>                                                                   用户在RememberMe时
<shiro:hasAnyRoles name="abc,123" >                       在有abc或者123角色时
<shiro:hasRole name="abc">                                                       拥有角色abc
<shiro:lacksRole name="abc">                                            没有角色abc
<shiro:hasPermission name="abc">                                           拥有权限资源abc
<shiro:lacksPermission name="abc">                                          没有abc权限资源
<shiro:principal>                                                                                      默认显示用户名称






  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hspringh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值