学习与使用Spring Security2(一)
Spring Security2是一套安全验证框架,与它的前一个版本acegi相比,简化了很多配置的工作,因为很多配置都已经自动完成了。下面就开始体验一下Spring Security2配置的简单与强大。在本文中将介绍Spring Security2的基本使用。
1, 新建一个J2EE Web工程。
2, 添加必须的jar包放到classpath中:
- spring.jar
- spring-security-core-2.0.4.jar
- spring-security-core-tiger-2.0.4.jar
3, 添加Spring Security的配置文件。在WEB-INF目录下建Application-Security.xml文件。并加入以下配置信息。
<?xml version=”1.0″ encoding=”UTF-8″?>
<beans:beans xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xmlns=http://www.springframework.org/schema/security
xmlns:beans=http://www.springframework.org/schema/beans
xsi:schemalocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-2.0.4.xsd”>
<http auto-config=”true”>
<intercept-url access=”ROLE_USER” pattern=”/**” />
</http>
<authentication-provider>
<user-service>
<user authorities=”ROLE_USER, ROLE_ADMIN” password=”hand” name=”hand” />
<user authorities=”ROLE_USER” password=”test” name=”test” />
</user-service>
</authentication-provider>
</beans:beans>
4, 在web.xml中配置一个filter来拦截所有的请求,并使用2中的配置信息来验证用户的合法性,如下:
<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app version=”2.4″
xmlns=”http://java.sun.com/xml/ns/j2ee”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class> org.springframework.web.filter.DelegatingFilterProxy </filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
5.测试,将这个项目发布到web,访问http://localhost:<port>/<projectname>,就可以看到如下的登录页面:
使用第2步中配置的用户名密码password=”hand” name=”hand”登录。登录成功表示已经学会了如何使用Spring Security2
来进行最基本的Web应用安全控制了。
无相关文章.
欢迎hailor多发表Java开源相关的技术总结和项目经验。