`

SSH项目中加入spring security(三)-- 将URL资源放入数据库配置

阅读更多

这篇博客,我是自己边学习边写,算是学习笔记。我知道深度不够,但是用于初学者学习入门应该还是不错的,各位看官轻拍吻

进入正题。。。

先给出上两篇的链接吧

SSH项目中加入spring security(一) 

SSH项目中加入spring security(二)--加入自定义数据表

我们一般做权限管理会用五个表来管理,分别有用户表、权限表、角色表、用户角色表和角色权限表,所以上一篇里面那种结构不能用到实际情况下面。

表结构

 创建表的sql,放入示例数据:

CREATE TABLE `user_role` (
  `id` char(32) NOT NULL,
  `role_id` char(32) DEFAULT NULL,
  `user_id` char(32) DEFAULT NULL,
  `create_date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


insert  into `user_role`(`id`,`role_id`,`user_id`,`create_date`) values ('402846814019e1b0014019e27eed0000','402846814019e1b0014019e27eed0000','402846814019e1b0014019e27eed0000','2013-07-29 00:00:00'),('402846814019e1b0014019e27eed0001','402846814019e1b0014019e27eed0001','402846814019e1b0014019e27eed0000','2013-07-29 00:00:00'),('402846814019e1b0014019e27eed0002','402846814019e1b0014019e27eed0001','402846814019e1b0014019e27eed0001','2013-07-29 00:00:00');

CREATE TABLE `privilege` (
  `id` char(32) NOT NULL,
  `pri_no` varchar(4) DEFAULT NULL,
  `pri_name` varchar(128) DEFAULT NULL,
  `pri_url` varchar(256) DEFAULT NULL,
  `disable` tinyint(1) DEFAULT '0',
  `create_date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `privilege`(`id`,`pri_no`,`pri_name`,`pri_url`,`disable`,`create_date`) values ('402846814019e1b0014019e27eed0000','1001','','/admin.jsp',0,NULL),('402846814019e1b0014019e27eed0001','1002','','/**',0,NULL);

CREATE TABLE `role` (
  `id` char(32) NOT NULL,
  `role_no` varchar(4) DEFAULT NULL,
  `role_name` varchar(128) DEFAULT NULL,
  `role_des` varchar(512) DEFAULT NULL,
  `disable` tinyint(1) DEFAULT '0',
  `creat_date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `role`(`id`,`role_no`,`role_name`,`role_des`,`disable`,`creat_date`) values ('402846814019e1b0014019e27eed0000','1','ROLE_ADMIN','管理员角色',0,NULL),('402846814019e1b0014019e27eed0001','2','ROLE_USER','用户角色',0,NULL);

CREATE TABLE `role_pri` (
  `id` char(32) NOT NULL,
  `role_id` char(32) DEFAULT NULL,
  `pri_id` char(32) DEFAULT NULL,
  `create_date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `role_pri`(`id`,`role_id`,`pri_id`,`create_date`) values ('402846814019e1b0014019e27eed0000','402846814019e1b0014019e27eed0000','402846814019e1b0014019e27eed0001',NULL),('402846814019e1b0014019e27eed0001','402846814019e1b0014019e27eed0001','402846814019e1b0014019e27eed0001',NULL),('402846814019e1b0014019e27eed0002','402846814019e1b0014019e27eed0000','402846814019e1b0014019e27eed0000',NULL);


CREATE TABLE `user` (
  `id` char(32) NOT NULL,
  `username` varchar(64) DEFAULT NULL,
  `pwd` varchar(64) DEFAULT NULL,
  `enabled` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `user`(`id`,`username`,`pwd`,`enabled`) values ('402846814019e1b0014019e27eed0000','admin','admin',1),('402846814019e1b0014019e27eed0001','sozhike','111111',1);

 上一篇中URL资源的配置方式:

<intercept-url pattern="/admin.jsp" access="ROLE_ADMIN" />
<intercept-url pattern="/**" access="ROLE_USER" />

 所以我们得到这个结构的sql是:

select pr.pri_url,ro.role_name
from privilege as pr
join role_pri as rp
on pr.id = rp.pri_id
join role as ro
on ro.id = rp.role_id

 

接下来,我们需要对spring security进行扩展

将下面的类加入到项目当中

package com.sozhike.common.utils;

import java.sql.ResultSet;
import java.sql.SQLException;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.FactoryBean;

import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.object.MappingSqlQuery;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.ConfigAttributeEditor;
import org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.AntPathRequestMatcher;
import org.springframework.security.web.util.RequestMatcher;


public class JdbcFilterInvocationDefinitionSourceFactoryBean
    extends JdbcDaoSupport implements FactoryBean {
    private String resourceQuery;

    public boolean isSingleton() {
        return true;
    }

    public Class getObjectType() {
        return FilterInvocationSecurityMetadataSource.class;
    }

    /**
     * 使用urlMatcher和requestMap创建DefaultFilterInvocationDefinitionSource。
     */
    public Object getObject() {
        return new DefaultFilterInvocationSecurityMetadataSource(this
            .buildRequestMap());
    }

    /**
     * 这样我们可以执行它的execute()方法获得所有资源信息。
     * @return
     */
    protected Map<String, String> findResources() {
        ResourceMapping resourceMapping = new ResourceMapping(getDataSource(),
                resourceQuery);

        Map<String, String> resourceMap = new LinkedHashMap<String, String>();

        for (Resource resource : (List<Resource>) resourceMapping.execute()) {
            String url = resource.getUrl();
            String role = resource.getRole();

            if (resourceMap.containsKey(url)) {
                String value = resourceMap.get(url);
                resourceMap.put(url, value + "," + role);
            } else {
                resourceMap.put(url, role);
            }
        }

        return resourceMap;
    }

    /**
     * 使用获得的资源信息组装requestMap。
     * @return
     */
    protected LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> buildRequestMap() {
        LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap =
            null;
        requestMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();

        ConfigAttributeEditor editor = new ConfigAttributeEditor();

        Map<String, String> resourceMap = this.findResources();

        for (Map.Entry<String, String> entry : resourceMap.entrySet()) {
            String key = entry.getKey();
            editor.setAsText(entry.getValue());
            requestMap.put(new AntPathRequestMatcher(key),
                (Collection<ConfigAttribute>) editor.getValue());
        }

        return requestMap;
    }

    public void setResourceQuery(String resourceQuery) {
        this.resourceQuery = resourceQuery;
    }

    private class Resource {
        private String url;
        private String role;

        public Resource(String url, String role) {
            this.url = url;
            this.role = role;
        }

        public String getUrl() {
            return url;
        }

        public String getRole() {
            return role;
        }
    }

    /**
     * 定义一个MappingSqlQuery实现数据库操作
     * @author Administrator
     *
     */
    private class ResourceMapping extends MappingSqlQuery {
        protected ResourceMapping(DataSource dataSource,
            String resourceQuery) {
            super(dataSource, resourceQuery);
            compile();
        }

        protected Object mapRow(ResultSet rs, int rownum)
            throws SQLException {
            String url = rs.getString(1);
            String role = rs.getString(2);
            Resource resource = new Resource(url, role);

            return resource;
        }
    }
}

 替换原有功能的切入点,在spring配置(确保您之前的SSH框架是通的哟)的bean中加入我们刚写的类:

	<!-- 配置spring security -->
    <bean id="filterSecurityInterceptor" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor" autowire="byType">
        <property name="securityMetadataSource" ref="filterInvocationSecurityMetadataSource" />
        <property name="authenticationManager" ref="org.springframework.security.authenticationManager"/>
    </bean>

    <bean id="filterInvocationSecurityMetadataSource"
        class="com.sozhike.common.utils.JdbcFilterInvocationDefinitionSourceFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="resourceQuery" value="
			select pr.pri_url,ro.role_name
			from szk_sys_privilege as pr
			join szk_sys_rolepri as rp
			on pr.id = rp.pri_id
			join szk_sys_role as ro
			on ro.id = rp.role_id
        "/>
    </bean>

 修改applicationContext-security.xml中<http>的配置

     <http auto-config="true">
	    <custom-filter ref="filterSecurityInterceptor" before="FILTER_SECURITY_INTERCEPTOR" />
	</http>

到现在,我们 applicationContext-security.xml的内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    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-3.0.xsd
                        http://www.springframework.org/schema/security 
                        http://www.springframework.org/schema/security/spring-security-3.1.xsd">

 
     <http auto-config="true">
	    <custom-filter ref="filterSecurityInterceptor" before="FILTER_SECURITY_INTERCEPTOR" />
	</http>
  		
 	<authentication-manager>
    	<authentication-provider>
	      	<jdbc-user-service data-source-ref="dataSource"
            users-by-username-query="select u.username,u.pwd,u.enabled
									from user as u
									where u.username = ?"
            authorities-by-username-query="select u.username,r.role_name
										from user as u
										join szk_sys_permission as p
										on u.id = p.user_id
										join szk_sys_role as r
										on r.id = p.role_id
										where u.username = ?"/>
    	</authentication-provider>
  	</authentication-manager>

</beans:beans>

 

上面这些步骤做完的话,重启你的项目,再试试admin/admin跟sozhike/111111登录,是不是已经成功了呢?

 

 

 

原创文章,转载请标明出处(http://sunliyings17.iteye.com/admin/blogs/1915466),谢谢

 

 

  • 大小: 46.3 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics