使用Shiro的JdbcRealm做权限简单实现

新接一个项目,着急使用权限功能,就先没写Realm扩展类直接使用JdbcRealm了。已经建好了5个表:用户,角色,权限,和两个中间表,重写了JdbcRealm的三个Query属性:authenticationQuery,userRolesQuery,permissionsQuery。配置时还要把permissionsLookupEnabled属性设置为true,否则permissionsQuery不能执行,将会查不到权限表里的数据。
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="jdbcRealm"/>
    </bean>

    <bean id="jdbcRealm" class="org.apache.shiro.realm.jdbc.JdbcRealm">
        <property name="dataSource" ref="dataSource"/>
        <property name="permissionsLookupEnabled" value="true"/>
        <property name="authenticationQuery" value="select password from rms_user where login_name = ?" />
        <property name="userRolesQuery" value="select r.role_code from rms_role r,rms_user u,rms_user_role ur where r.id = ur.role_id and u.id = ur.user_id and u.login_name = ?"/>
        <property name="permissionsQuery" value="select distinct p.priv_code from rms_privilege p,rms_role r,rms_role_privilege rp where p.id = rp.priv_id and r.id = rp.role_id and r.role_code = ?"/>
    </bean>
	
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <property name="loginUrl" value="/login"/>
        <property name="successUrl" value="/main"/>
        <property name="unauthorizedUrl" value="/login"/>
        <property name="filterChainDefinitions">
            <value>
                /login = authc
				/logout = logout
				/static/** = anon
				/** = authc
            </value>
        </property>
    </bean>
</beans>

进入页面后,权限表中priv_code有"user:view"数据,所对应的角色和用户,就能看见Shiro标签里的内容。
<shiro:user>
<shiro:hasPermission name="user:view">
<div>用户管理</div>
</shiro:hasPermission>
</shiro:user>

猜你喜欢

转载自cwx714.iteye.com/blog/1674559