SpringSecurity简介
- Spring Security 是一个能够为基于 Spring 的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在 Spring 应用上下文中配置的 Bean,充分利用了Spring IoC,DI(控制反转 Inversion of Control ,DI:Dependency Injection 依赖注入)和 AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。
SpringSecurity 实现登录功能
引入spring-security-web和spring-security-config依赖
创建web.xml,其中定义配置文件spring-security.xml的contextConfigLocation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17<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>- 注意:此步骤中springSecurityFilterChain名称不可自定义,spring框架的底层源码中已定义该名称。
创建配置文件spring-security.xml
1
2
3
4
5
6
7
8
9
10
11
12
13<!-- 页面拦截规则 -->
<http use-expressions="false">
<intercept-url pattern="/**" access="ROLE_USER" />
<form-login/>
</http>
<!-- 认证管理器 -->
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="123456" authorities="ROLE_USER"/>
</user-service>
</authentication-provider>
</authentication-manager>配置说明:
intercept-url 表示拦截页面(/* 表示的是该目录下的资源,只包括本级目录不包括下级目录;/** 表示的是该目录以及该目录下所有级别子目录的资源)
form-login 为开启表单登陆
use-expressions :是否允许SpEL,默认为 true。当为true时,拦截url应写成如下形式:
1
<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />