SpringMVC整合Shiro,Shiro是一個強大易用的Java安全框架,提供了認證、授權、加密和會話管理等功能。
第一步:配置web.xml
<!-- 配置Shiro過濾器,先讓Shiro過濾系統接收到的請求 --> <!-- 這里filter-name必須對應applicationContext.xml中定義的<bean id="shiroFilter"/> --> <!-- 使用[/*]匹配所有請求,保證所有的可控請求都經過Shiro的過濾 --> <!-- 通常會將此filter-mapping放置到最前面(即其他filter-mapping前面),以保證它是過濾器鏈中第一個起作用的 --> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <!-- 該值缺省為false,表示生命周期由SpringApplicationContext管理,設置為true則表示由ServletContainer管理 --> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
第二步:配置applicationContext.xml
<!-- 繼承自AuthorizingRealm的自定義Realm,即指定Shiro驗證用戶登錄的類為自定義的ShiroDbRealm.java --> <bean id="myRealm" class="com.jadyer.realm.MyRealm"/> <!-- Shiro默認會使用Servlet容器的Session,可通過sessionMode屬性來指定使用Shiro原生Session --> <!-- 即<property name="sessionMode" value="native"/>,詳細說明見官方文檔 --> <!-- 這里主要是設置自定義的單Realm應用,若有多個Realm,可使用'realms'屬性代替 --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="myRealm"/> </bean> <!-- Shiro主過濾器本身功能十分強大,其強大之處就在於它支持任何基於URL路徑表達式的、自定義的過濾器的執行 --> <!-- Web應用中,Shiro可控制的Web請求必須經過Shiro主過濾器的攔截,Shiro對基於Spring的Web應用提供了完美的支持 --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!-- Shiro的核心安全接口,這個屬性是必須的 --> <property name="securityManager" ref="securityManager"/> <!-- 要求登錄時的鏈接(可根據項目的URL進行替換),非必須的屬性,默認會自動尋找Web工程根目錄下的"/login.jsp"頁面 --> <property name="loginUrl" value="/"/> <!-- 登錄成功后要跳轉的連接(本例中此屬性用不到,因為登錄成功后的處理邏輯在LoginController里硬編碼為main.jsp了) --> <!-- <property name="successUrl" value="/system/main"/> --> <!-- 用戶訪問未對其授權的資源時,所顯示的連接 --> <!-- 若想更明顯的測試此屬性可以修改它的值,如unauthor.jsp,然后用[玄玉]登錄后訪問/admin/listUser.jsp就看見瀏覽器會顯示unauthor.jsp --> <property name="unauthorizedUrl" value="/"/> <!-- Shiro連接約束配置,即過濾鏈的定義 --> <!-- 此處可配合我的這篇文章來理解各個過濾連的作用http://blog.csdn.net/jadyer/article/details/12172839 --> <!-- 下面value值的第一個'/'代表的路徑是相對於HttpServletRequest.getContextPath()的值來的 --> <!-- anon:它對應的過濾器里面是空的,什么都沒做,這里.do和.jsp后面的*表示參數,比方說login.jsp?main這種 --> <!-- authc:該過濾器下的頁面必須驗證后才能訪問,它是Shiro內置的一個攔截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter --> <property name="filterChainDefinitions"> <value> /mydemo/login=anon /mydemo/getVerifyCodeImage=anon /main**=authc /user/info**=authc /admin/listUser**=authc,perms[admin:manage] </value> </property> </bean> <!-- 保證實現了Shiro內部lifecycle函數的bean執行 --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> <!-- 開啟Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP掃描使用Shiro注解的類,並在必要時進行安全邏輯驗證 --> <!-- 配置以下兩個bean即可實現此功能 --> <!-- Enable Shiro Annotations for Spring-configured beans. Only run after the lifecycleBeanProcessor has run --> <!-- 由於本例中並未使用Shiro注解,故注釋掉這兩個bean(個人覺得將權限通過注解的方式硬編碼在程序中,查看起來不是很方便,沒必要使用) --> <!-- <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> -->
第三步:自定義的Realm類
public class MyRealm extends AuthorizingRealm { /** * 為當前登錄的Subject授予角色和權限 * @see 經測試:本例中該方法的調用時機為需授權資源被訪問時 * @see 經測試:並且每次訪問需授權資源時都會執行該方法中的邏輯,這表明本例中默認並未啟用AuthorizationCache * @see 個人感覺若使用了Spring3.1開始提供的ConcurrentMapCache支持,則可靈活決定是否啟用AuthorizationCache * @see 比如說這里從數據庫獲取權限信息時,先去訪問Spring3.1提供的緩存,而不使用Shior提供的AuthorizationCache */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){ //獲取當前登錄的用戶名,等價於(String)principals.fromRealm(this.getName()).iterator().next() String currentUsername = (String)super.getAvailablePrincipal(principals); // List<String> roleList = new ArrayList<String>(); // List<String> permissionList = new ArrayList<String>(); // //從數據庫中獲取當前登錄用戶的詳細信息 // User user = userService.getByUsername(currentUsername); // if(null != user){ // //實體類User中包含有用戶角色的實體類信息 // if(null!=user.getRoles() && user.getRoles().size()>0){ // //獲取當前登錄用戶的角色 // for(Role role : user.getRoles()){ // roleList.add(role.getName()); // //實體類Role中包含有角色權限的實體類信息 // if(null!=role.getPermissions() && role.getPermissions().size()>0){ // //獲取權限 // for(Permission pmss : role.getPermissions()){ // if(!StringUtils.isEmpty(pmss.getPermission())){ // permissionList.add(pmss.getPermission()); // } // } // } // } // } // }else{ // throw new AuthorizationException(); // } // //為當前用戶設置角色和權限 // SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo(); // simpleAuthorInfo.addRoles(roleList); // simpleAuthorInfo.addStringPermissions(permissionList); SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo(); //實際中可能會像上面注釋的那樣從數據庫取得 if(null!=currentUsername && "mike".equals(currentUsername)){ //添加一個角色,不是配置意義上的添加,而是證明該用戶擁有admin角色 simpleAuthorInfo.addRole("admin"); //添加權限 simpleAuthorInfo.addStringPermission("admin:manage"); System.out.println("已為用戶[mike]賦予了[admin]角色和[admin:manage]權限"); return simpleAuthorInfo; } //若該方法什么都不做直接返回null的話,就會導致任何用戶訪問/admin/listUser.jsp時都會自動跳轉到unauthorizedUrl指定的地址 //詳見applicationContext.xml中的<bean id="shiroFilter">的配置 return null; } /** * 驗證當前登錄的Subject * @see 經測試:本例中該方法的調用時機為LoginController.login()方法中執行Subject.login()時 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { //獲取基於用戶名和密碼的令牌 //實際上這個authcToken是從LoginController里面currentUser.login(token)傳過來的 //兩個token的引用都是一樣的 UsernamePasswordToken token = (UsernamePasswordToken)authcToken; System.out.println("驗證當前Subject時獲取到token為" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE)); // User user = userService.getByUsername(token.getUsername()); // if(null != user){ // AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), user.getNickname()); // this.setSession("currentUser", user); // return authcInfo; // }else{ // return null; // } //此處無需比對,比對的邏輯Shiro會做,我們只需返回一個和令牌相關的正確的驗證信息 //說白了就是第一個參數填登錄用戶名,第二個參數填合法的登錄密碼(可以是從數據庫中取到的,本例中為了演示就硬編碼了) //這樣一來,在隨后的登錄頁面上就只有這里指定的用戶和密碼才能通過驗證 if("mike".equals(token.getUsername())){ AuthenticationInfo authcInfo = new SimpleAuthenticationInfo("mike", "mike", this.getName()); this.setSession("currentUser", "mike"); return authcInfo; } //沒有返回登錄用戶名對應的SimpleAuthenticationInfo對象時,就會在LoginController中拋出UnknownAccountException異常 return null; } /** * 將一些數據放到ShiroSession中,以便於其它地方使用 * @see 比如Controller,使用時直接用HttpSession.getAttribute(key)就可以取到 */ private void setSession(Object key, Object value){ Subject currentUser = SecurityUtils.getSubject(); if(null != currentUser){ Session session = currentUser.getSession(); System.out.println("Session默認超時時間為[" + session.getTimeout() + "]毫秒"); if(null != session){ session.setAttribute(key, value); } } } }
Shiro 權限管理filterChainDefinitions過濾器配置
前言:shiro三大核心模塊:Subject(用戶)、SecurityManager(框架心臟)、Realm(Shiro與應用安全數據間的“橋梁”)
SecurityManager去管理cacheManager緩存和sessionManager會話,sessionManager再去管理sessionDAO會話DAO 和sessionIdCookie會話ID生成器和sessionValidationScheduler會話驗證調度器,cacheManager通過使用Ehcache實現,Realm通過自己自定義或者其他方式的權限存儲來實現,比如登錄等.
使用統一數據訪問層,通過編寫實體類,編寫Repository接口,最后通過配置文件實現
Repository是標識,spring自動掃描,CrudRepository繼承Repository實現curd,PagingAndSortingRepository繼承CrudRepository實現分頁排序,JpaRepository繼承PagingAndSortingRepository實現JPA規范相關的方法,JpaSpecificationExecutor不屬於Repository,比較特殊,它去實現一組JPA Criteria查詢相關的方法
/**
* Shiro-1.2.2內置的FilterChain
* @see =========================================================================================================
* @see 1)Shiro驗證URL時,URL匹配成功便不再繼續匹配查找(所以要注意配置文件中的URL順序,尤其在使用通配符時)
* @see 故filterChainDefinitions的配置順序為自上而下,以最上面的為准
* @see 2)當運行一個Web應用程序時,Shiro將會創建一些有用的默認Filter實例,並自動地在[main]項中將它們置為可用
* @see 自動地可用的默認的Filter實例是被DefaultFilter枚舉類定義的,枚舉的名稱字段就是可供配置的名稱
* @see anon—————org.apache.shiro.web.filter.authc.AnonymousFilter
* @see authc————–org.apache.shiro.web.filter.authc.FormAuthenticationFilter
* @see authcBasic———org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter
* @see logout————-org.apache.shiro.web.filter.authc.LogoutFilter
* @see noSessionCreation–org.apache.shiro.web.filter.session.NoSessionCreationFilter
* @see perms————–org.apache.shiro.web.filter.authz.PermissionAuthorizationFilter
* @see port—————org.apache.shiro.web.filter.authz.PortFilter
* @see rest—————org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter
* @see roles————–org.apache.shiro.web.filter.authz.RolesAuthorizationFilter
* @see ssl—————-org.apache.shiro.web.filter.authz.SslFilter
*@see user—————org.apache.shiro.web.filter.authz.UserFilter
* @see =========================================================================================================
* @see 3)通常可將這些過濾器分為兩組
* @see anon,authc,authcBasic,user是第一組認證過濾器
* @see perms,port,rest,roles,ssl是第二組授權過濾器
* @see 注意user和authc不同:當應用開啟了rememberMe時,用戶下次訪問時可以是一個user,但絕不會是authc,因為authc是需要重新認證的
* @see user表示用戶不一定已通過認證,只要曾被Shiro記住過登錄狀態的用戶就可以正常發起請求,比如rememberMe
* @see 說白了,以前的一個用戶登錄時開啟了rememberMe,然后他關閉瀏覽器,下次再訪問時他就是一個user,而不會authc
* @see ==========================================================================================================
* @see 4)舉幾個例子
* @see /admin=authc,roles[admin] 表示用戶必需已通過認證,並擁有admin角色才可以正常發起’/admin’請求
* @see /edit=authc,perms[admin:edit] 表示用戶必需已通過認證,並擁有admin:edit權限才可以正常發起’/edit’請求
* @see /home=user 表示用戶不一定需要已經通過認證,只需要曾經被Shiro記住過登錄狀態就可以正常發起’/home’請求
* @see ==========================================================================================================
* @see 5)各默認過濾器常用如下(注意URL Pattern里用到的是兩顆星,這樣才能實現任意層次的全匹配)
* @see /admins/**=anon 無參,表示可匿名使用,可以理解為匿名用戶或游客
* @see /admins/user/**=authc 無參,表示需認證才能使用
* @see /admins/user/**=authcBasic 無參,表示httpBasic認證
* @see /admins/user/**=user 無參,表示必須存在用戶,當登入操作時不做檢查
* @see /admins/user/**=ssl 無參,表示安全的URL請求,協議為https
* @see /admins/user/*=perms[user:add:]
* @see 參數可寫多個,多參時必須加上引號,且參數之間用逗號分割,如/admins/user/*=perms[“user:add:,user:modify:*”]
* @see 當有多個參數時必須每個參數都通過才算通過,相當於isPermitedAll()方法
* @see /admins/user/**=port[8081]
* @see 當請求的URL端口不是8081時,跳轉到schemal://serverName:8081?queryString
* @see 其中schmal是協議http或https等,serverName是你訪問的Host,8081是Port端口,queryString是你訪問的URL里的?后面的參數
* @see /admins/user/**=rest[user]
* @see 根據請求的方法,相當於/admins/user/**=perms[user:method],其中method為post,get,delete等
* @see /admins/user/**=roles[admin]
* @see 參數可寫多個,多個時必須加上引號,且參數之間用逗號分割,如/admins/user/**=roles[“admin,guest”]
* @see 當有多個參數時必須每個參數都通過才算通過,相當於hasAllRoles()方法
* @see
http://liureying.blog.163.com/blog/static/61513520136205574873/
spring中 shiro logout 配置方式
有兩種方式實現logout
1. 普通的action中 實現自己的logout方法,取到Subject,然后logout
這種需要在ShiroFilterFactoryBean 中配置 filterChainDefinitions
對應的action的url為a
# some example chain definitions:
/index.htm = anon
/logout = anon
/unauthed = anon
/console/** = anon
/css/** = anon
/js/** = anon
/lib/** = anon
/admin/** = authc, roles[admin]
/docs/** = authc, perms[document:read]
/** = authc
# more URL-to-FilterChain definitions here
使用shiro提供的logout filter
需要定義 相應的bean
然后將相應的url filter配置為logout如下
<property name="filterChainDefinitions"> <value> # some example chain definitions: /index.htm = anon /logout = logout /unauthed = anon /console/** = anon /css/** = anon /js/** = anon /lib/** = anon /admin/** = authc, roles[admin] /docs/** = authc, perms[document:read] /** = authc # more URL-to-FilterChain definitions here </value>
注:anon,authcBasic,auchc,user是認證過濾器,perms,roles,ssl,rest,port是授權過濾器
最終 各種參數配置詳解
anon:例子/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沒有參數表示必須存在用戶,當登入操作時不做檢查
注:anon,authcBasic,auchc,user是認證過濾器,
perms,roles,ssl,rest,port是授權過濾器