<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    菜園子

    BlogJava 首頁 新隨筆 聯系 聚合 管理
      7 Posts :: 1 Stories :: 31 Comments :: 0 Trackbacks

    Shiro權限框架

    開發系統中,少不了權限,目前java里的權限框架有SpringSecurity和Shiro(以前叫做jsecurity),對于SpringSecurity:功能太過強大以至于功能比較分散,使用起來也比較復雜,跟Spring結合的比較好。對于初學Spring Security者來說,曲線還是較大,需要深入學習其源碼和框架,配置起來也需要費比較大的力氣,擴展性也不是特別強。

    對于新秀Shiro來說,好評還是比較多的,使用起來比較簡單,功能也足夠強大,擴展性也較好。聽說連Spring的官方都不用Spring Security,用的是Shiro,足見Shiro的優秀。網上找到兩篇介紹:http://www.infoq.com/cn/articles/apache-shiro http://www.ibm.com/developerworks/cn/opensource/os-cn-shiro/,官網http://shiro.apache.org/ ,使用和配置起來還是比較簡單。下面只是簡單介紹下我們是如何配置和使用Shiro的(暫時只用到了Shiro的一部分,沒有配置shiro.ini文件)。

    首先是添加過濾器,在web.xml中:

    <filter>

    <filter-name>shiroFilter</filter-name>

    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>

    <init-param>

                <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>

    權限的認證類:

    public class ShiroDbRealm extends AuthorizingRealm {

        @Inject

        private UserService userService ;

        

        /**

     * 認證回調函數,登錄時調用.

     */

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) 
    throws AuthenticationException {

    UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

    User useruserService.getUserByUserId(token.getUsername());

    if (user!= null) {  

        return new SimpleAuthenticationInfo(user.getUserId(), user.getUserId(), getName());

    else {

    return null;

    }

    }

    /**

     * 授權查詢回調函數, 進行鑒權但緩存中無用戶的授權信息時調用.

     */

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

    String loginName = (String) principals.fromRealm(getName()).iterator().next();

    User useruserService.getUserByUserId(loginName);

    if (user != null) {

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

    info.addStringPermission("common-user");

    return info;

    else {

    return null;

    }

    }

    }

    Spring的配置文件:

    <?xml version="1.0" encoding="UTF-8"?>

    <beans >

    <description>Shiro Configuration</description>

    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"/>

    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">

    <property name="realm" ref="shiroDbRealm" />

    </bean>

    <bean id="shiroDbRealm" class="com.company.service.common.shiro.ShiroDbRealm" />

        <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">

            <property name="securityManager" ref="securityManager"/>

            <property name="loginUrl" value="/common/security/login" />

            <property name="successUrl" value="/common/security/welcome" />

            <property name="unauthorizedUrl" value="/common/security/unauthorized"/>

            <property name="filterChainDefinitions">

                <value>

                    /resources/** = anon

                    /manageUsers = perms[user:manage]

                    /** = authc

                </value>

            </property>

        </bean>

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

        <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>

    </beans>

    登錄的Controller:

    @Controller

    @RequestMapping(value = "/common/security/*")

    public class SecurityController {

        @Inject

        private UserService userService;

        @RequestMapping(value = "/login")

        public String login(String loginName, String password,
    HttpServletResponse response, HttpServletRequest request) throws Exception {

            User user = userService.getUserByLogin(loginName);

                if (null != user) {

                    setLogin(loginInfoVO.getUserId(), loginInfoVO.getUserId());

                    return "redirect:/common/security/welcome";

                } else {

                    return "redirect:/common/path?path=showLogin";

                }

        };

        public static final void setLogin(String userId, String password) {

            Subject currentUser = SecurityUtils.getSubject();

            if (!currentUser.isAuthenticated()) {

                //collect user principals and credentials in a gui specific manner 

                //such as username/password html form, X509 certificate, OpenID, etc.

                //We'll use the username/password example here since it is the most common.

                //(do you know what movie this is from? ;)

                UsernamePasswordToken token = new UsernamePasswordToken(userId, password);

                //this is all you have to do to support 'remember me' (no config - built in!):

                token.setRememberMe(true);

                currentUser.login(token);

            }

        };

        

        @RequestMapping(value="/logout")

        @ResponseBody

        public void logout(HttpServletRequest request){

            Subject subject = SecurityUtils.getSubject();

            if (subject != null) {           

                subject.logout();

            }

            request.getSession().invalidate();

        };

    }

    注冊和獲取當前登錄用戶:

        public static final void setCurrentUser(User user) {

            Subject currentUser = SecurityUtils.getSubject();

            if (null != currentUser) {

                Session session = currentUser.getSession();

                if (null != session) {

                    session.setAttribute(Constants.CURRENT_USER, user);

                }

            }

        };

        public static final User getCurrentUser() {

            Subject currentUser = SecurityUtils.getSubject();

            if (null != currentUser) {

                Session session = currentUser.getSession();

                if (null != session) {

                    User user = (User) session.getAttribute(Constants.CURRENT_USER);

                    if(null != user){

                        return user;

                    }

    }

    }

        };

    需要的jar包有3個:shiro-core.jar,shiro-spring.jar,shiro-web.jar。感覺shiro用起來比SpringSecurity簡單很多。



    QQ:24889356
    posted on 2011-09-16 21:36 GhostZhang 閱讀(32442) 評論(14)  編輯  收藏

    Feedback

    # re: Shiro權限框架 2011-09-17 08:55 tb
    恩 比較不錯   回復  更多評論
      

    # re: Shiro權限框架 2011-09-17 17:20 rox
    正好在看appfuse和springside4的樣例,謝謝了。  回復  更多評論
      

    # re: Shiro權限框架 2011-09-17 22:59 wison
    我現在唯一還有疑問的就是,這個數據庫表中的字段,怎么設計。怎么查詢出來。望樓主解釋。3Q  回復  更多評論
      

    # re: Shiro權限框架 2011-09-18 07:58 GhostZhang
    這個只是系統權限,不是業務權限。所以表設計的話,我猜你指的是業務權限的表設計吧。shiro不涉及。  回復  更多評論
      

    # re: Shiro權限框架 2011-09-19 09:22 wison
    @GhostZhang
    嗯,我說的是業務權限表的設計,好吧,我們不談權限設置。僅僅談登錄,登錄總需要獲得帳號密碼,和數據庫中的比對吧。如何驗證,不清楚是需要我們自己去寫還是shiro已經封裝好了。我僅僅是不清楚這個地方。3Q樓主。  回復  更多評論
      

    # re: Shiro權限框架 2011-09-19 14:27 GhostZhang
    @wison
    這個需要自己寫。  回復  更多評論
      

    # re: Shiro權限框架 2011-09-20 09:22 wison
    @GhostZhang
    OK,3Q  回復  更多評論
      

    # re: Shiro權限框架 2012-02-29 22:50 唐文韜
    你好,我在整合shiro和spring的過程中,我只要給control加@RequiresAuthentication 類似的這種注解,在項目啟動的時候就報錯
    Caused by: org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.
    at org.springframework.aop.framework.DefaultAopProxyFactory.createAopProxy(DefaultAopProxyFactory.java:67)
    at org.springframework.aop.framework.ProxyCreatorSupport.createAopProxy(ProxyCreatorSupport.java:104)
    at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:112)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:476)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:362)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:407)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1461)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    ... 35 more

    可是當我把cglib.jar的包加進去的時候還是報錯,期待您的解答  回復  更多評論
      

    # re: Shiro權限框架[未登錄] 2012-03-04 09:30 ghostzhang
    cglib-nodep-2.2.jar
    我用的是這個,添加@RequiresAuthentication,啟動沒問題。  回復  更多評論
      

    # re: Shiro權限框架 2012-04-25 16:37 wgw
    @唐文韜

    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
    depends-on="lifecycleBeanPostProcessor">
    <property name="proxyTargetClass" value="true" /> <!-- 和struts結合使用必須把該屬性設置為true,否則使用注解出錯 -->
    </bean>
    OK  回復  更多評論
      

    # re: Shiro權限框架 2014-03-11 13:09 JSON
    頁面怎么獲取session  回復  更多評論
      

    # re: Shiro權限框架[未登錄] 2015-12-05 15:34 1
    1111  回復  更多評論
      

    # re: Shiro權限框架 2016-03-21 14:58 11
    32  回復  更多評論
      


    只有注冊用戶登錄后才能發表評論。


    網站導航:
     
    主站蜘蛛池模板: 亚洲免费视频播放| 三上悠亚电影全集免费 | 亚洲性色成人av天堂| 免费看一区二区三区四区| 亚洲精品无码Av人在线观看国产| 免费夜色污私人影院网站| mm1313亚洲精品国产| 国产成人1024精品免费| 亚洲中文字幕日产乱码高清app| 国产亚洲精品免费视频播放| 国产成人A人亚洲精品无码| 日本在线免费播放| 亚洲第一成年人网站| 久久不见久久见免费影院| 亚洲av成人片在线观看| 免费一级做a爰片久久毛片潮喷| 免费夜色污私人影院网站电影| 亚洲人成色77777| 91成人免费观看| 亚洲成年网站在线观看| 免费a在线观看播放| 青柠影视在线观看免费高清| 亚洲综合综合在线| 国产精品色午夜免费视频| 精品人妻系列无码人妻免费视频| 亚洲欧洲第一a在线观看| 99久久这里只精品国产免费| 色偷偷亚洲第一综合网| 亚洲精品中文字幕无码蜜桃| 成年人免费的视频| 亚洲AV女人18毛片水真多| 亚洲中文久久精品无码ww16| 国产精品入口麻豆免费观看| 立即播放免费毛片一级| 亚洲AV无码一区二区乱子伦| 欧美a级在线现免费观看| 国产伦精品一区二区免费| 亚洲成aⅴ人片在线影院八| 免费一级毛片不卡不收费| 久久久久高潮毛片免费全部播放 | 亚洲a∨无码一区二区|