SpringSecurity3基础篇

时间:2023-03-09 20:15:34
SpringSecurity3基础篇

Spring Security 是一种基于Spring AOP 和Servlet过滤器的安全框架,它提供了全面的安全性解决方案,同时在Web请求级和方法调用级处理身份确认和授权。在Spring Framework基础上,Spring Security 充分利用了依赖注入(DI,Dependency Injection)和面向切面技术。

Spring Security3.0.7 下载解压后的dist目录中有两个war包,这两个war包是实例程序,将其中一个contacts实例程序的.war扩展名改成.rar,将其解压出来,将解压出来的WEB-INF/lib下所有jar包拷贝到我们的工程中。

SpringSecurity3基础篇

首先配置web.xml文件,内容如下:

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext-security.xml
</param-value>
</context-param> <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>

Spring Security 的配置

applicationContext-security.xml的配置可以在下载的文档或事例中找到,如下

<?xml version="1.0" encoding="UTF-8"?>
<b:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:b="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.0.xsd">     <http auto-config="true">
        <intercept-url pattern="/**" access="ROLE_USER"/>
    </http> <!-- 配置认证管理器-->
    <authentication-manager>
        <authentication-provider>
<user-service>
<user name="user" password="user" authorities="ROLE_USER"/>
</user-service>
        </authentication-provider>
    </authentication-manager>
</b:beans>

将项目部署到web服务器中,然后访问index.jsp,我们发现首页并没有出现,而是跳到登录页面上。因为项目刚启动,第一次访问的时候,没有任何用户登录,而在配置文件中我们拦截的是所有的请求,所以第一次请求被拦截了。

SpringSecurity3基础篇

输入刚才配置文件中配置的user和password,提交后发现能够正确进入首页index.jsp

问题:那个登录页面哪儿来的?

当有请求过来的时候,Spring security 框架开始检查要访问的资源是否有权访问,如果当前登录用户无权或者当前根本就没有用户登录,则Spring Securtiy框架就自动产生一个登录页面。当前登录页面进行正确登录后,Spring security会自动进行登录验证,如果成功登录,将用户信息放到session中,然后转到先前请求的页面上。