Spring安全权限管理(Spring Security) . (一)

2014-11-24 09:56:31 · 作者: · 浏览: 3

1.Spring Security简要介绍

Spring Security以前叫做acegi,是后来才成为Spring的一个子项目,也是目前最为流行的一个安全权限管理框架,它与Spring紧密结合在一起。

Spring Security关注的重点是在企业应用安全层为您提供服务,你将发现业务问题领域存在着各式各样的需求。银行系统跟电子商务应用就有很大的不同。电子商务系统与企业销售自动化工具又有很大不同。这些客户化需求让应用安全显得有趣,富有挑战性而且物有所值。Spring Security为基于J2EE的企业应用软件提供了一套全面的安全解决方案。

2.为Spring Security配置过滤器和其他参数

要使用Spring Security,首先就是在web.xml中为它配置过滤器, 其次因为我的spring配置文件是放在WEB-INF下的,因此还要配置上下文的参数,最后添加spring的监听器:


[xhtml]
< xml version="1.0" encoding="UTF-8" >
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">


contextConfigLocation
/WEB-INF/spring-*.xml



springSecurityFilterChain

org.springframework.web.filter.DelegatingFilterProxy



springSecurityFilterChain
/*



org.springframework.web.context.ContextLoaderListener



index.jsp


BASIC


3.配置security(spring-security.xml)


[xhtml]
< xml version="1.0" encoding="UTF-8" >

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-2.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">







logout-success-url="/j_spring_security_check" />









4.数据源的配置(spring-common.xml)


[c-sharp]
< xml version="1.0" encoding="UTF-8" >
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-2.5.xsd">


class="org.apache.commons.dbcp.BasicDataSource">
value="com.mysql.jdbc.Driver">










5.项目的目录结构

6. 数据库脚本


[xhtml]
/-- 注意这里的脚本是MYSQL的,因此在你演示这个实例的时候,要加入MySQL的驱动包 --/

create table users
(
username varchar(50) primary key,
password varchar(50),
enabled tinyint(1)
);

create table authorities
(
id int auto_increment primary key,
username varchar(50),
authority varchar(50),
constraint fk_authorities_users foreign key(username) references users(username)
);

create unique index ix_auth_username on authorities (username,authority);

\

7.部署和配置的要点说明

这是一个Spring Security的数据库认证实例,要注意以下几点:
(1)请自行加入Spring必须的包,Spring security的包和MySQL的驱动包,当然你也可以换成其他的数据库,但是你要相应的修改spring-common.xml中的dataSource部分
(2)数据库中的两个表users,authorites必须完全按照脚本所示来定义,也就是说表的名字不能修改.
(3)users表必须包含username,password,enabled字段,这三个字段是绝对不能少的,也不能修改类型.另外enabled一定要为1才能登录
(4)authorities表必须包含username字段,这个字段引用users的username作为外键,authority字段就是角色的名字,角色名字必须满足ROLE_XXX的格式(例如:ROLE_ADMIN,ROLE_USER,ROLE_MAMAGER)
(5)如果一个用户有多个角色,不要将多个角色放在一起用逗号隔开.而是每个角色定义一条记录(例如:abu有ROLE_ADMIN,RO