許可權系統--通過shiro進行按鈕及頁面訪問url的許可權控制
一:問題的引入
前面雖然基本的功能都有了但是頁面按鈕的控制與url的控制還是沒有處理。這麼一個場景,雖然使用者只能通過點選選單進行各個介面的訪問,假如使用者知道了你的介面的訪問url,直接跳過選單訪問的話,正常來說是不應該跳轉到對應的介面上的。如果不對其進行控制,也會造成許可權混亂的。就像下圖這樣:可以看出選單中確實沒有許可權資源控制這個選單,按道理是無法進去那個介面的。也做到了許可權的控制。
但是當我們直接訪問url時卻又進來對應的介面。這種情況是一定要避免的。
二:問題解決:
這就要說道shiro這個強大的工具了。
當面我們每次登入系統時,都會通過我們自己定義的繼承AuthorizingRealm的ShiroRealm進行使用者賬號密碼的確認以及擁有許可權的查詢:
自定義shiroReam
public class ShiroDbRealm extends AuthorizingRealm { @Autowired private UserService userService; @Autowired private SysUserService sysUserService ; @Autowired private SysUserResService sysUserResService ; public ShiroDbRealm() { super(); } /** * 驗證登陸 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; SysUser sysUser = sysUserService.getUserByLoginName(token.getUsername()) ; //根據登入名獲取使用者資訊 if (sysUser != null) { return new SimpleAuthenticationInfo(sysUser.getUserNo(), sysUser.getUserPwd(), getName()); } else { throw new AuthenticationException(); } } /** * 登陸成功之後,進行角色和許可權驗證 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { String userNo = (String) getAvailablePrincipal(principals); // 列舉此使用者所有的許可權 //List<Permission> permissions = userService.findUserPermissionByName(username); List<SysUserRes> listRes = sysUserResService.getPermissionByNo(userNo) ; Set<String> strs=new HashSet<String>(); Iterator<SysUserRes> it = listRes.iterator(); while (it.hasNext()) { SysUserRes re=it.next(); strs.add(re.getResUrl()); } SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); authorizationInfo.addStringPermissions(strs); return authorizationInfo; } /** * 清除所有使用者授權資訊快取. */ public void clearCachedAuthorizationInfo(String principal) { SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName()); clearCachedAuthorizationInfo(principals); } /** * 清除所有使用者授權資訊快取. */ public void clearAllCachedAuthorizationInfo() { Cache<Object, AuthorizationInfo> cache = getAuthorizationCache(); if (cache != null) { for (Object key : cache.keys()) { cache.remove(key); } } } /** * * @Title: clearAuthz * @Description: TODO 清楚快取的授權資訊 * @return void 返回型別 */ public void clearAuthz(){ this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals()); } }
我們在對應位置加上斷點:
(1)進行使用者賬號密碼的驗證
(2)進行已經擁有許可權的查詢:
系統會先查詢擁有哪些許可權。
(3)通過siro進行處理:shiro的配置檔案
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans classpath:org/springframework/beans/factory/xml/spring-beans-3.0.xsd http://www.springframework.org/schema/context classpath:org/springframework/context/config/spring-context-3.0.xsd http://www.springframework.org/schema/aop classpath:org/springframework/aop/config/spring-aop-3.0.xsd http://www.springframework.org/schema/tx classpath:org/springframework/transaction/config/spring-tx-3.0.xsd http://www.springframework.org/schema/util classpath:org/springframework/beans/factory/xml/spring-util-3.0.xsd" default-lazy-init="true"> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="shiroDbRealm" /> <property name="cacheManager" ref="shiroCacheManager" /> </bean> <!-- 專案自定義的Realm --> <bean id="shiroDbRealm" class="com.creidtsys.security.realm.ShiroDbRealm"> <!-- <property name="credentialsMatcher"> <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> <property name="hashAlgorithmName" value="MD5"/> </bean> </property> --> </bean> <!-- Shiro Filter --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <property name="loginUrl" value="/page/login" /> <property name="successUrl" value="/page/index" /> <property name="unauthorizedUrl" value="/page/noPers" /> <!-- <property name="filters"> <util:map> <entry key="authc"> <bean class="org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter"/> </entry> </util:map> </property> --> <property name="filterChainDefinitions"> <value> /sysUser/checkLogin = anon /login = anon /index = anon /page/** = anon <!-- 要攔截的url --> <!-- 使用者許可權攔截 --> /sysUser/list= perms["user:serch"] /sysUser/toAdd = perms["user:add"] /sysUser/toEdit = perms["user:update"] <!-- 角色許可權攔截 --> /sysRole/list=perms["role:serch"] /sysUser/toAdd = perms["role:add"] /sysUser/toEdit = perms["role:update"] <!-- 部門許可權攔截 --> /sysDept/list = perms["dept:serch"] /sysDept/toAdd = perms["dpt:add"] /sysDept/toEdit = perms["dept:edit"] <!-- 資源許可權攔截 --> /sysRes/list = perms["res:serch"] /sysRes/toAdd = perms["res:add"] /sysRest/toEdit = perms["res:edit"] </value> </property> </bean> <!-- 使用者授權資訊Cache org.apache.shiro.cache.ehcache.EhCacheManager--> <bean id="shiroCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> <property name="cacheManager" ref="ehCacheManager" /> </bean> <!-- 保證實現了Shiro內部lifecycle函式的bean執行 --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /> <!-- AOP式方法級許可權檢查 --> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"> </bean> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager" /> </bean> </beans>
(4)攔截配置說明:
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是授權過濾器
(5)我的配置:
/sysRes/list = perms["res:serch"]
/sysRes/toAdd = perms["res:add"]
/sysRest/toEdit = perms["res:edit"]
如果你想要訪問主介面(/sysRes/list)就必修又有["res:serch"]的許可權
如果你想要跳轉到新增介面(/sysRes/toAdd),就必須擁有["res:add"]的許可權
如果你想跳轉到修改介面(/sysRest/toEdit),就必須擁有["res:edit"]的許可權
這樣就出現下面的結果了:
三:按鈕許可權的控制
按鈕許可權的控制就顯得簡單了,只需要通過shiro的標籤就輕而易舉的解決了:
<div data-options="region:'center'">
<div id="tb" style="padding-bottom: 5px">
<input id="queryName" class="easyui-textbox"/>
<a id="querybtn" class="easyui-linkbutton" data-options="iconCls:'icon-search'">查詢</a>
<shiro:hasPermission name="res:add">
<a id="addbtn" class="easyui-linkbutton" data-options="iconCls:'icon-add'">新增</a>
</shiro:hasPermission>
<shiro:hasPermission name="res:edit">
<a id="editbtn" class="easyui-linkbutton" data-options="iconCls:'icon-edit'">修改</a>
</shiro:hasPermission>
<shiro:hasPermission name="res:delete">
<a id="delbtn" class="easyui-linkbutton" data-options="iconCls:'icon-remove'">刪除 </a>
</shiro:hasPermission>
</div>