基於dobbo作服務開發後一般會趕上這樣一些問題,舉個例子:用戶的筆記,涉及到CRUD 4個接口,是每個接口中都要把用戶傳進去麼?
好比:刪除接口
定義爲 noteService.deleteById(Long noteId)
仍是 noteService.deleteById(Long userId, Long noteId)
若是是前者,這個時候若是不驗證用戶對資源是否有權限直接刪除是否合理,尤爲是這種可能被用戶猜到的ID很容易被惡意調用。若是選第二種的話,那麼有不少接口都要這樣定義,感受不夠美觀,並且也不夠嚴謹。css
先說說個人想法:假定全部的服務調用都要經過filter,這個filter可以將sessionId以隱性的方式傳參,這樣就不用每個接口去增長userId這個參數,同時因爲sessionID是由場門的服務生成的無心義的隨機字符,通常相似UUID,當服務端收到這個sessionID後,經過調用session遠程服務去獲取當前用戶的信息,這樣服務端就能夠知道當前用戶是誰,這也避免了消費端的失誤形成了用戶數據的篡改的可能。html
根據設想,將shiro設計成兩個模塊:ucenter-session-api和ucenter-session-provider,其它的服務端都須要對ucenter-session-api依賴,用於受權web服務對ucenter-session-provider依賴。java
RemoteSessionServiceweb
package com.lenxeon.ucenter.session.api; import com.lenxeon.ucenter.session.pojo.PermissionContext; import org.apache.shiro.session.Session; import java.io.Serializable; public interface RemoteSessionService { /** * 獲取session * @param sessionId * @return */ Session getSession(Serializable sessionId); /** * 建立session * @param session * @return */ Serializable createSession(Session session); /** * 更新session * @param session */ void updateSession(Session session); /** * 刪除session * @param session */ void deleteSession(Session session); /** * 查詢用戶的角色和權限信息 * @param identify * @return */ PermissionContext getPermissions(String identify); }
ShiroCustomFilter,主要是追加x-session-idspring
package com.lenxeon.ucenter.session.dubbo; import com.alibaba.dubbo.rpc.*; import com.lenxeon.ucenter.session.api.RemoteSessionService; import com.lenxeon.utils.io.JsonUtils; import org.apache.commons.lang.StringUtils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ShiroCustomFilter implements Filter { final static Logger logger = LoggerFactory.getLogger(ShiroCustomFilter.class); public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { if(invoker.getInterface().equals(RemoteSessionService.class)){ //去獲取信息 }else{ //追加補充信息 String sessionId = ""; Subject subject = SecurityUtils.getSubject(); if (subject.isAuthenticated()) { //判斷是否登錄過 } sessionId = subject.getSession().getId().toString(); invocation.getAttachments().put("x-session-id", StringUtils.defaultString(sessionId)); } logger.info("CustomFilter.login[{}]", JsonUtils.toJson(invocation.getAttachments())); Result result = invoker.invoke(invocation); return result; } }
MyResultapache
package com.lenxeon.ucenter.session.dubbo; import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.Result; import java.util.concurrent.Callable; class MyResult implements Callable<Result> { private Invoker<?> invoker; private Invocation invocation; public MyResult(Invoker<?> invoker, Invocation invocation) { this.invocation = invocation; this.invoker = invoker; } @Override public Result call() throws Exception { Result result = invoker.invoke(invocation); return result; } }
spring-client-shiro.xmlapi
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <aop:config proxy-target-class="true"/> <!-- 會話ID生成器 --> <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/> <bean id="myRealm" class="com.lenxeon.ucenter.session.shiro.client.ClientRealm"> <property name="cachingEnabled" value="false"/> <property name="remoteSessionService" ref="remoteSessionService"></property> </bean> <!-- 會話Cookie模板 --> <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie"> <constructor-arg value="${client.session.id}"/> <property name="httpOnly" value="true"/> <property name="maxAge" value="-1"/> <property name="domain" value="${client.cookie.domain}"/> <property name="path" value="${client.cookie.path}"/> </bean> <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie"> <constructor-arg value="${client.rememberMe.id}"/> <property name="httpOnly" value="true"/> <property name="maxAge" value="2592000"/><!-- 30天 --> <property name="domain" value="${client.cookie.domain}"/> <property name="path" value="${client.cookie.path}"/> </bean> <!-- 會話DAO --> <bean id="sessionDAO" class="com.lenxeon.ucenter.session.shiro.client.ClientSessionDAO"> <property name="sessionIdGenerator" ref="sessionIdGenerator"/> <property name="remoteSessionService" ref="remoteSessionService"/> </bean> <!-- 會話管理器 --> <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> <property name="deleteInvalidSessions" value="false"/> <property name="sessionValidationSchedulerEnabled" value="false"/> <property name="sessionDAO" ref="sessionDAO"/> <property name="sessionIdCookieEnabled" value="false"/> <!--<property name="sessionIdCookie" ref="sessionIdCookie"/>--> </bean> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <!--<bean id="securityManager" class="org.apache.shiro.mgt.DefaultSecurityManager">--> <property name="realms" ref="myRealm"/> <property name="sessionManager" ref="sessionManager"/> </bean> <!-- Shiro生命週期處理器--> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager"/> </bean> <!-- 至關於調用SecurityUtils.setSecurityManager(securityManager) --> <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/> <property name="arguments" ref="securityManager"/> </bean> </beans>
RemoteSessionServiceImpl瀏覽器
package com.lenxeon.ucenter.session.api.impl; import com.alibaba.dubbo.config.annotation.Reference; import com.google.common.collect.Sets; import com.lenxeon.apps.commons.api.IdService; import com.lenxeon.ucenter.session.api.RemoteSessionService; import com.lenxeon.ucenter.session.pojo.PermissionContext; import com.lenxeon.ucenter.user.api.SecurityService; import org.apache.shiro.session.Session; import org.apache.shiro.session.mgt.eis.SessionDAO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.Serializable; @Service public class RemoteSessionServiceImpl implements RemoteSessionService { @Autowired private SessionDAO sessionDAO; @Reference(version = "1.0.0") private IdService idService; @Reference(version = "1.0.0") private SecurityService securityService; private static final Logger logger = LoggerFactory.getLogger(RemoteSessionServiceImpl.class); @Override public Session getSession(Serializable sessionId) { return sessionDAO.readSession(sessionId); } @Override public Serializable createSession(Session session) { return sessionDAO.create(session); } @Override public void updateSession(Session session) { sessionDAO.update(session); } @Override public void deleteSession(Session session) { sessionDAO.delete(session); } @Override public PermissionContext getPermissions(String identify) { PermissionContext permissionContext = new PermissionContext(); permissionContext.setRoles(Sets.newHashSet("po", "sm", "team")); permissionContext.setPermissions(Sets.newHashSet("system:delete_department", "system:user:create", "system:user:delete")); return permissionContext; } }
spring-local-shiro.xml安全
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd"> <aop:config proxy-target-class="true"/> <!-- 會話ID生成器 --> <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/> <bean id="limitRetryHashedMatcher" class="com.lenxeon.ucenter.session.shiro.local.LimitRetryHashedMatcher"> <!--這個配置要和PassWordUtils裏一致--> <property name="hashAlgorithmName" value="md5"></property> <property name="hashIterations" value="2"></property> <property name="storedCredentialsHexEncoded" value="true"></property> </bean> <!-- Shiro默認會使用Servlet容器的Session,可經過sessionMode屬性來指定使用Shiro原生Session --> <!-- 即<property name="sessionMode" value="native"/>,詳細說明見官方文檔 --> <!-- 這裏主要是設置自定義的單Realm應用,如有多個Realm,可以使用'realms'屬性代替 --> <!-- 會話DAO --> <bean id="sessionDAO" class="com.lenxeon.ucenter.session.shiro.local.RedisSessionDAO"> <property name="sessionIdGenerator" ref="sessionIdGenerator"/> <property name="expire" value="1800000"/> </bean> <!--<!– 會話驗證調度器 –>--> <!--<bean id="sessionValidationScheduler"--> <!--class="com.lenxeon.ucenter.user.shiro.shiro.QuartzSessionValidationScheduler">--> <!--<property name="sessionValidationInterval" value="1800000"/>--> <!--<property name="sessionManager" ref="sessionManager"/>--> <!--</bean>--> <!-- 會話ID生成器 --> <bean id="sessionFactory" class="com.lenxeon.ucenter.session.shiro.local.UserSessionFactory"/> <!-- 會話管理器 --> <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> <!--<bean id="sessionManager" class="org.apache.shiro.session.mgt.DefaultSessionManager">--> <property name="globalSessionTimeout" value="1800000"/> <property name="deleteInvalidSessions" value="true"/> <property name="sessionValidationSchedulerEnabled" value="true"/> <!--<property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>--> <property name="sessionDAO" ref="sessionDAO"/> <property name="sessionFactory" ref="sessionFactory"/> <property name="sessionIdCookie.path" value="/"/> </bean> <dubbo:reference id="userService" interface="com.lenxeon.ucenter.user.api.UserService" version="1.0.0"/> <!-- 繼承自AuthorizingRealm的自定義Realm,即指定Shiro驗證用戶登陸的類爲自定義的ShiroDbRealm.java --> <bean id="myRealm" class="com.lenxeon.ucenter.session.shiro.local.UserRealm"> <property name="userService" ref="userService"></property> <property name="credentialsMatcher" ref="limitRetryHashedMatcher"></property> </bean> <bean id="cacheManger" class="com.lenxeon.ucenter.session.shiro.local.RedisCacheManager"/> <!--<bean id="securityManager" class="com.lenxeon.ucenter.user.shiro.MyDefaultSecurityManager">--> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realms"> <list> <ref bean="myRealm"/> </list> </property> <property name="cacheManager" ref="cacheManger"/> <property name="sessionManager" ref="sessionManager"/> </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(我的以爲將權限經過註解的方式硬編碼在程序中,查看起來不是很方便,不必使用) --> <!-- Support Shiro Annotation --> <!--<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">--> <!--<property name="exceptionMappings">--> <!--<props>--> <!--<prop key="org.apache.shiro.authz.UnauthorizedException">shiro-test/refuse</prop>--> <!--</props>--> <!--</property>--> <!--</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> <!-- 至關於調用SecurityUtils.setSecurityManager(securityManager) --> <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/> <property name="arguments" ref="securityManager"/> </bean> </beans>
須要依賴:ucenter-session-api
須要配置:shiroCustomFilter
須要引用: spring-client-shiro.xmlcookie
<import resource="classpath*:META-INF/spring/spring-local-shiro.xml"/> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager"/> </bean> <!--我應該考慮本身實現一個dobbo的filter--> <!-- 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="http://localhost:8092/users/login"/> <!-- 登陸成功後要跳轉的鏈接(本例中此屬性用不到,由於登陸成功後的處理邏輯在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="successUrl" value="/welcome/index"/> <property name="filterChainDefinitions"> <value> *.js = anon *.css=anon /modules/**=anon /static/**=anon /weixin/**=anon /users/forget.html=anon /users/reset.html=anon /users/login.html=anon /users/**=anon /oauth2/**==anon /test/**==anon <!--/api/**=anon--> /api/v1/users/random=anon /api/v1/users/sign_in=anon /api/v1/users/login=anon /api/v1/users/session=anon /api/v1/users/mobile/check=anon /api/v1/users/password/forgot=anon /api/v1/users/password/reset=anon /api/v1/users/email/check=anon /api/v1/security/captcha/**=anon /api/ids**=anon /api/ids/**=anon /**=authc <!--/admin/**=authc--> <!--/apps-web/admin/**=authc--> <!--/mydemo/getVerifyCodeImage=anon--> <!--/main**=authc--> <!--/user/info**=authc--> <!--/admin/listUser**=authc,perms[admin:manage]--> </value> </property> </bean>