Spring整合Shiro做許可權控制模組詳細案例分析,shiro許可權控制

來源:互聯網
上載者:User

Spring整合Shiro做許可權控制模組詳細案例分析,shiro許可權控制
1.引入Shiro的Maven依賴

<!-- Spring 整合Shiro需要的依賴 --><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>1.2.1</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-web</artifactId><version>1.2.1</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-ehcache</artifactId><version>1.2.1</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.2.1</version></dependency><!-- 除此之外還有一些東西也不可少spring, spring-mvc, ibatis等 spring.3.1.2 spring-mvc.3.1.2 ibatis.2.3.4 cglib.2.2 -->
2.web.xml中配置
<!-- 配置shiro的核心攔截器 --><filter>  <filter-name>shiroFilter</filter-name>  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  </filter>  <filter-mapping>  <filter-name>shiroFilter</filter-name>  <url-pattern>/*</url-pattern>  </filter-mapping>
3.    編寫自己的UserRealm類繼承自Realm,主要實現認證和授權的管理操作
package com.jay.demo.shiro;import java.util.HashSet;import java.util.Iterator;import java.util.Set;import org.apache.shiro.authc.AuthenticationException;import org.apache.shiro.authc.AuthenticationInfo;import org.apache.shiro.authc.AuthenticationToken;import org.apache.shiro.authc.LockedAccountException;import org.apache.shiro.authc.SimpleAuthenticationInfo;import org.apache.shiro.authc.UnknownAccountException;import org.apache.shiro.authz.AuthorizationInfo;import org.apache.shiro.authz.SimpleAuthorizationInfo;import org.apache.shiro.realm.AuthorizingRealm;import org.apache.shiro.subject.PrincipalCollection;import org.springframework.beans.factory.annotation.Autowired;import com.jay.demo.bean.Permission;import com.jay.demo.bean.Role;import com.jay.demo.bean.User;import com.jay.demo.service.UserService;public class UserRealm extends AuthorizingRealm{@Autowiredprivate UserService userService;/** * 授權操作 */@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {//String username = (String) getAvailablePrincipal(principals);String username = (String) principals.getPrimaryPrincipal();Set<Role> roleSet =  userService.findUserByUsername(username).getRoleSet();//角色名稱的集合Set<String> roles = new HashSet<String>();//許可權名的集合Set<String> permissions = new HashSet<String>();Iterator<Role> it = roleSet.iterator();while(it.hasNext()){roles.add(it.next().getName());for(Permission per:it.next().getPermissionSet()){permissions.add(per.getName());}}SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();authorizationInfo.addRoles(roles);authorizationInfo.addStringPermissions(permissions);return authorizationInfo;}/** * 身分識別驗證操作 */@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {String username = (String) token.getPrincipal();User user = userService.findUserByUsername(username);if(user==null){//木有找到使用者throw new UnknownAccountException("沒有找到該帳號");}/* if(Boolean.TRUE.equals(user.getLocked())) {              throw new LockedAccountException(); //帳號鎖定          } *//** * 交給AuthenticatingRealm使用CredentialsMatcher進行密碼匹配,如果覺得人家的不好可以在此判斷或自訂實現   */SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),getName());return info;}@Overridepublic String getName() {return getClass().getName();}}
4.在Spring的applicationContext.xml中進行Shiro的相關配置

1、添加shiroFilter定義 

Xml代碼 

2、添加securityManager定義 

Xml代碼 

3、添加realm定義 

Xml代碼 

4、配置EhCache

< bean   id = "cacheManager"   class = "org.apache.shiro.cache.ehcache.EhCacheManager"   />

5、 保證實現了Shiro內部lifecycle函數的bean執行

<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

特別注意:

如果使用Shiro相關的註解,需要在springmvc-servlet.xml中配置一下資訊

<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/><bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">    <property name="securityManager" ref="securityManager"/></bean>
備忘:Shiro許可權管理的過濾器解釋:
預設過濾器(10個) anon -- org.apache.shiro.web.filter.authc.AnonymousFilterauthc -- org.apache.shiro.web.filter.authc.FormAuthenticationFilterauthcBasic -- org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilterperms -- org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilterport -- org.apache.shiro.web.filter.authz.PortFilterrest -- org.apache.shiro.web.filter.authz.HttpMethodPermissionFilterroles -- org.apache.shiro.web.filter.authz.RolesAuthorizationFilterssl -- org.apache.shiro.web.filter.authz.SslFilteruser -- org.apache.shiro.web.filter.authc.UserFilterlogout -- org.apache.shiro.web.filter.authc.LogoutFilteranon:例子/admins/**=anon 沒有參數,表示可以匿名使用。 authc:例如/admins/user/**=authc表示需要認證(登入)才能使用,沒有參數 roles:例子/admins/user/**=roles[admin],參數可以寫多個,多個時必須加上引號,並且參數之間用逗號分割,當有多個參數時,例如admins/user/**=roles["admin,guest"],每個參數通過才算通過,相當於hasAllRoles()方法。 perms:例子/admins/user/**=perms[user:add:*],參數可以寫多個,多個時必須加上引號,並且參數之間用逗號分割,例如/admins/user/**=perms["user:add:*,user:modify:*"],當有多個參數時必須每個參數都通過才通過,想當於isPermitedAll()方法。 rest:例子/admins/user/**=rest[user],根據請求的方法,相當於/admins/user/**=perms[user:method] ,其中method為post,get,delete等。 port:例子/admins/user/**=port[8081],當請求的url的連接埠不是8081是跳轉到schemal://serverName:8081?queryString,其中schmal是協議http或https等,serverName是你訪問的host,8081是url配置裡port的連接埠,queryString是你訪問的url裡的?後面的參數。 authcBasic:例如/admins/user/**=authcBasic沒有參數表示httpBasic認證 ssl:例子/admins/user/**=ssl沒有參數,表示安全的url請求,協議為https user:例如/admins/user/**=user沒有參數表示必須存在使用者,當登入操作時不做檢查

想瞭解更多詳細請點擊源碼地址擷取mingli

有興趣的朋友們可以前往球球哦~一起分享學習技術:2042849237

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.