1.1.1 SpringSecurity认证原理
SpringSecurity认证基本原理:
其中:
1:整个过滤器链由很多过滤器组成;
2:表单登录和HttpBasic只是其中一种过滤方式;
3:HttpBasic过滤方式在表单登录之后;
4:适配器“FilterSecurityInterceptor
”是过滤器链最后一环,决定请求最终能否访问目标资源服务。
5:根据认证失败原因由过滤器“ExceptionTranslationFilter
”进行处理。
1.1.2 SpringSecurity过滤器链
在工程配置文件web.xml中配置SpringSecurity过滤器:
其中类“org.springframework.web.filter.DelegatingFilterProxy
”是过滤器代理。
其本质作用:
Spring容器无法管理JavaEE容器中的实例,所以将代理过滤器定义在JavaEE容器中并通过该代理过滤器将所有请求委托给Spring容器中的过滤器。
配置文件web.xml内容:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<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>
<!-- 启动Spring容器服务 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
classpath:spring-security.xml
</param-value>
</context-param>
<!-- 启动Spring MVC服务 -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!-- 服务器启动时启动 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
1.1.3 SpringSecurity的基本配置
在工程配置文件spring-security.xml中的配置内容:
注:以上配置为使用“HttpBasic
”的登录认证方式。
配置文件“spring-security.xml”的内容:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
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">
<security:http>
<security:http-basic/>
</security:http>
<security:authentication-manager>
</security:authentication-manager>
</beans>
对于拦截资源的配置使用“security:intercept-url
”进行配置:
一级目录拦截使用“/*”,对于多级目录拦截使用“/**”,如下图所示: