<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  回復  更多評論
      


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


    網站導航:
     
    主站蜘蛛池模板: 在线看片无码永久免费视频| 中国毛片免费观看| 免费看国产精品3a黄的视频 | 日韩免费一区二区三区| 亚洲免费观看网站| 久久精品免费一区二区喷潮| 亚洲a级片在线观看| 成人男女网18免费视频| aⅴ免费在线观看| 亚洲精品在线免费看| 免费观看激色视频网站(性色)| 亚洲天堂一区在线| 免费观看的a级毛片的网站| 亚洲精品天堂成人片AV在线播放| 午夜网站免费版在线观看| 美女视频黄a视频全免费网站色| 免费在线视频一区| 国产一级a毛一级a看免费视频 | 国产91在线免费| 美景之屋4在线未删减免费| 国产亚洲美女精品久久久| 久久午夜免费鲁丝片| 亚洲午夜电影在线观看高清| 精品国产免费观看一区| 国产人成网在线播放VA免费| 久久精品国产亚洲av四虎| 国产一卡二卡3卡四卡免费| 国产精品成人亚洲| 久久91亚洲人成电影网站| 午夜性色一区二区三区免费不卡视频| 亚洲av永久无码精品秋霞电影秋| 亚洲男人的天堂一区二区| 99re在线这里只有精品免费| 亚洲影院天堂中文av色| 国产成人综合亚洲AV第一页| 亚洲网站免费观看| 免费人成视频在线观看免费| 99久久亚洲精品无码毛片| mm1313亚洲精品国产| 男人的天堂av亚洲一区2区| 亚洲精品美女久久久久99|