springSecurity是一个能为基于spring的企业应用系统,提供 声明式的安全访问控制解决方案的安全框架。
它为应用系统提供声明式的安全访问控制功能,减少为企业系统安全控制而编写大量重复代码的工作。
下面通过一个简单的springSecurity示例讲解springSecurity
1、在MyEclipse中新建项目SpringSecurity1,并导入springSecurity所需要的jar包
项目结构图,如下:
项目必须导入的jar包,如下:
2、在config下新建springSecurity的核心配置文件spring-security.xml,代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:sec="http://www.springframework.org/schema/security"
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.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<sec:http auto-config="true">
<sec:intercept-url pattern="/**" access="ROLE_USER"/>
</sec:http>
<sec:authentication-manager>
<sec:authentication-provider>
<sec:user-service>
<sec:user name="admin" password="123456" authorities="ROLE_USER"/>
<sec:user name="user" password="123456" authorities="ROLE_USER,ROLE_ADMIN"/>
</sec:user-service>
</sec:authentication-provider>
</sec:authentication-manager>
</beans>
配置详解:
1)、auto-config:没有建立登录页面,为什么springSecurity会跳转到登录页面?因为我们设置http的auto-config=true时
springSecurity会自动为我们生成。
当指定http元素的auto-config=true时,相当于
<security:http>
<security:form-login />
<security:http-basic />
<security:logout />
</security:http>
intercept-url:用于定义一个权限控制的规则
pattern属性用于表示我们将对哪些url进行权限控制,也可以写成一个正则表达式
pattern="/**" 表示我们将对所有的url进行权限控制
access属性,表示在请求对应的URL时需要什么权限
ROLE_USER:表示请求的用户应当具有ROLE_USER角色,ROLE_是一个提示spring使用基于角色的检查的标记
authentication-manager:用于处理来自于框架其它部分的认证请求
authentication-provider:authenticationManager通过它来认证用户
userService:用来获取用户信息的
user:用于配置用户名称、密码和所拥有的权限
3、在web.xml中配置springSecurity的过滤器 ,配置过滤器后就可以控制对这个项目的每个请求了,代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
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_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-security.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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>
</web-app>
如果用户名输入user,密码输入123456或用户名输入admin,密码输入123456则登陆成功。否则登录失败