1 简介
Spring Security是Spring生态系统中的一员,提供安全机制的(软件的安全、程序的安全,非硬件安全)
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。
就帮我们解决两个问题
- 认证:验证用户名和密码是否合法(是否系统中用户),这是第一关;
- 授权:是系统用户不代表你能使用某些功能,因为你可能没有权限,这是第二关;
Spring Security底层使用的是过滤器,针对url进行的拦截,对应到java中也就是类; 因此被称为粗粒度授权验证,就是验证url,你当前用户有没有这个url的权限。
2 快速入门
省略父工程创建步骤,见:https://www.jianshu.com/p/8853bc384758
2.1 创建web项目
2.2 导入依赖
mytest_parent
com.mytest
1.0-SNAPSHOT
../mytest_parent/pom.xml
4.0.0
spring_security_01
war
org.apache.tomcat.maven
tomcat7-maven-plugin
2.2
80
/
org.springframework
spring-webmvc
org.springframework
spring-jdbc
org.springframework
spring-aspects
org.springframework
spring-test
org.springframework.security
spring-security-web
org.springframework.security
spring-security-config
jstl
jstl
javax.servlet
servlet-api
provided
javax.servlet
jsp-api
provided
2.3 配置applicationContext_security.xml, 配置认证和授权信息
2.4 配置过滤器
(这里的web.xml和index.jsp文件是手动创建的,名称路径一致即可)
Archetype Created Web Application
contextConfigLocation
classpath:spring/applicationContext_security.xml
springSecurityFilterChain
org.springframework.web.filter.DelegatingFilterProxy
springSecurityFilterChain
/*
org.springframework.web.context.ContextLoaderListener
index.jsp
2.5测试
打开tomcat插件测试访问localhost/index.jsp页面,如果当前用户没有登录认证的话,则跳转到SpringSecurity的内置登录页面
输入配置文件中配置好的账户名admin密码admin,会出现如下404
配置文件中增加,对网页缩略图的不拦截后,重启tomcat
即可访问到index.jsp页面
3 配置自定义的登录页面
3.1 登录页面login.jsp
<%@ page isELIgnored="false" contentType="text/html;charset=UTF-8" language="java"%>
xxx系统登录页
3.2 成功页面: success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
登录成功,欢迎!
3.3 失败页面: error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
登录失败!!!
3.4 配置
3.5 测试1: 访问登录页面(localhost/login.jsp) 且 用户名和密码正确
http://localhost/login.jsp
3.6 测试2:访问localhost/index.jsp, 用户名和密码正确:
关闭浏览器重新访问
http://localhost/index.jsp
3.7 测试3: 访问index.jsp, 用户名或密码错误
http://localhost/index.jsp