资料区
快速入门——自定义页面(工程):springSecurityTest.zip
一、Spring Security概述
1、Spring Security介绍

二、springsecurity的使用
1、快速入门分析图(默认登陆界面,用户、密码保存在配置文件)

快速入门演示
① 创建一个maven的有骨架的web工程(配置pom.xml)
其中包含了对应的springSecurity
<properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.7</maven.compiler.source><maven.compiler.target>1.7</maven.compiler.target><spring.version>5.0.2.RELEASE</spring.version><spring.security.version>5.0.1.RELEASE</spring.security.version></properties><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-web</artifactId><version>${spring.security.version}</version></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-config</artifactId><version>${spring.security.version}</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency></dependencies><build><plugins><!-- java编译插件 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.2</version><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding></configuration></plugin><plugin><groupId>org.apache.tomcat.maven</groupId><artifactId>tomcat7-maven-plugin</artifactId><configuration><!-- 指定端口 --><port>8090</port><!-- 请求路径 --><path>/</path></configuration></plugin></plugins></build>
② 配置web.xml
其中对应org.springframework.web.filter.DelegatingFilterProxy的名称一定要为:springSecurityFilterChain
<?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://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>SpringSecurity314</display-name>
<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>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
③ 配置SpringSecurity.xml

对应auto-config设置为true,会进行加载一些默认的配置,包含访问对应页面的登录
并且这里需要说明的是:这里设置的用户名、密码是通过配置文件的形式来进行保存的。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="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">
<security:http auto-config="true"
use-expressions="false">
<!-- intercept-url定义一个过滤规则 pattern表示对哪些url进行权限控制,ccess属性表示在请求对应
的URL时需要什么权限,
默认配置时它应该是一个以逗号分隔的角色列表,请求的用户只需拥有其中的一个角色就能成功访问对应
的URL -->
<security:intercept-url pattern="/**" access="ROLE_USER"/>
<!-- auto-config配置后,不需要在配置下面信息 <security:form-login /> 定义登录表单信息
<security:http-basic
/> <security:logout /> -->
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="user" password="{noop}user"
authorities="ROLE_USER"/>
<security:user name="admin" password="{noop}admin"
authorities="ROLE_ADMIN"/>
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
</beans>
运行测试(默认配置登陆页面)
因为我们pom.xml配置了对应的Tomcat插件,所以我们可以直接运行Tomcat
方式一:输入命令
mvn Tomcat7:run
方式二:点击右侧Maven的插件运行



权限不够的登陆情况:
2、使用自定义登陆页面(用户、密码保存在配置文件)
① 添加登陆、登陆成功与失败页面

login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title></head>
<body>
<form action="login" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="登录"/> <input type="reset" value="重置"/></td>
</tr>
</table>
</form>
</body>
</html>
② 更改springsecurity.xml,来设置对应登陆以及跳转页面

springsecurity.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="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">
<!-- 配置不过滤的资源(静态资源及登录相关) -->
<security:http security="none" pattern="/login.html" />
<security:http security="none" pattern="/failter.html" />
<security:http auto-config="true" use-expressions="false" >
<!-- 配置资料连接,表示任意路径都需要ROLE_USER权限 -->
<security:intercept-url pattern="/**" access="ROLE_USER" />
<!-- 自定义登陆页面,login-page 自定义登陆页面 authentication-failure-url 用户权限校验失败之后才会跳转到这个页面,如果数据库中没有这个用户则不会跳转到这个页面。
default-target-url 登陆成功后跳转的页面。 注:登陆页面用户名固定 username,密码 password,action:login -->
<security:form-login login-page="/login.html"
login-processing-url="/login" username-parameter="username"
password-parameter="password" authentication-failure-url="/failter.html"
default-target-url="/success.html" authentication-success-forward-url="/success.html"
/>
<!-- 关闭CSRF,跨服务器请求访问,默认是开启的 -->
<security:csrf disabled="true" />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="user" password="{noop}user"
authorities="ROLE_USER" />
<security:user name="admin" password="{noop}admin"
authorities="ROLE_ADMIN" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
</beans>
运行测试
admin与user两个都可以登陆成功
跳转页面

3、使用数据库来完成spring security的认证操作
在Spring Security中如果想要使用数据进行认证操作,有很多种操作方式,这里我们介绍使用UserDetails、 UserDetailsService来完成操作。

对应spring security配置文件中会指向对应的service层的实现类,而自定义的实现类应当继承UserDetails,并进行返回对应实现类来进行验证。
UserDetails
public interface UserDetails extends Serializable {
Collection<? extends GrantedAuthority> getAuthorities();
String getPassword();
String getUsername();
boolean isAccountNonExpired();
boolean isAccountNonLocked();
boolean isCredentialsNonExpired();
boolean isEnabled();
}
这个UserDetails需要自定义一个service层的接口来继承它(称为A),接着使用实现类B来实现A接口,
相当于间接继承UserDetails
UserDetails是一个接口,我们可以认为UserDetails作用是于封装当前进行认证的用户信息,但由于其是一个 接口,所以我们可以对其进行实现,也可以使用Spring Security提供的一个UserDetails的实现类User来完成 操作
以下是User类的部分代码
User
public class User implements UserDetails, CredentialsContainer {
private String password;
private final String username;
private final Set<GrantedAuthority> authorities;
private final boolean accountNonExpired; //帐户是否过期
private final boolean accountNonLocked; //帐户是否锁定
private final boolean credentialsNonExpired; //认证是否过期
private final boolean enabled; //帐户是否可用
}
UserDetailsService
public interface UserDetailsService {
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}
上面将UserDetails与UserDetailsService做了一个简单的介绍,那么我们具体如何完成Spring Security的数据库认 证操作哪,我们通过用户管理中用户登录来完成Spring Security的认证操作,可以去查看对应去权限管理系统中的对应部分来进行查看信息。
三、SpringSecurity的源码分析
1、web.xml文件中配置
问题:为什么DelegatingFilterProxy的filter-name必须是springSecurityFilterChain?
① 对应再web.xml中配置的filter(DelegatingFilterProxy)并不是真正的Filter,在其initFilterBean方法中会从WebApplicationContext根据delegate 来获取到。
② 通过在doFilter就去中我们会发现真正干活的其实是delegate这个Filter,而delegate其实就是FilterChainProxy
我们可以看到下面的源码:对应DelegatingFilterProxy继承了GenericFilterBean,GenericFilterBean也继承了Filter,其filter的生命周期执行顺序是构造器——init()初始化——doFilter()——destory()方法**

FilterChainProxy是spring在解析配置文件时装配到上下文中,并且beanName为springSecurityFilterChain,
因此在web.xml中需要配置filter-name为springSecurityFilterChain
2、SpringSecurity配置文件配置
对于http标签的配置的说明:
在配置文件中我们主要使用标签来过多成配置
对于我们对于数据库的使用操作为什么要继承usersDetailService?
这是源码分析流程:
四、权限控制
在服务器端我们可以通过Spring security提供的注解对方法来进行权限控制。Spring Security在方法的权限控制上 支持三种类型的注解,JSR-250注解、@Secured注解和支持表达式的注解,这三种注解默认都是没有启用的,需要 单独通过global-method-security元素的对应属性进行启用
1、服务器端方法级权限控制
① JSR-250注解
使用流程

spring-security配置文件中标签:
<!--开启jsr250注解-->
<security:global-method-security jsr250-annotations="enabled"/>
pom.xml配置:
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
使用注解:
@RolesAllowed("ADMIN")
参数描述

② Secured注解
使用流程
其中使用到了security的依赖jar包,在spring-security配置文件中配置
<!--开启secured注解-->
<security:global-method-security secured-annotations="enabled"/>
<!--使用Secured注解-->
@Secured("ROLE_ADMIN")
与JSR-250注解区别

③ 支持表达式注解方式
使用流程
在spring-security中配置
这里使用的两个方法分别表示:第一个是判断其name是否为tom,第二个是设置权限只有ADMIN的才能登陆
<security:global-method-security pre-post-annotations="enabled"/>
四个注解的使用方式

表达式介绍
Spring Security允许我们在定义URL访问或方法访问所应有的权限时使用Spring EL表达式,在定义所需的访问权限时如果对应的表达式返回结果为true则表示拥有对应的权限,反之则无。Spring Security可用表达式对象的基类是SecurityExpressionRoot,其为我们提供了如下在使用Spring EL表达式对URL或方法进行权限控制时通用的内置表达式。
| 表达式 | 描述 |
|---|---|
| hasRole([role]) | 当前用户是否拥有指定角色。 |
| hasAnyRole([role1,role2]) | 多个角色是一个以逗号进行分隔的字符串。如果当前用户拥有指定角色中的任意一个则返回true。 |
| hasAuthority([auth]) | 等同于hasRole |
| hasAnyAuthority([auth1,auth2]) | 等同于hasAnyRole |
| Principle | 代表当前用户的principle对象 |
| authentication | 直接从SecurityContext获取的当前Authentication对象 |
| permitAll | 总是返回true,表示允许所有的 |
| denyAll | 总是返回false,表示拒绝所有的 |
| isAnonymous() | 当前用户是否是一个匿名用户 |
| isRememberMe() | 表示当前用户是否是通过Remember-Me自动登录的 |
| isAuthenticated() | 表示当前用户是否已经登录认证成功了。 |
| isFullyAuthenticated() | 如果当前用户既不是一个匿名用户,同时又不是通过Remember-Me自动登录的,则返回true。 |
2、页面端权限控制介绍

导入配置
pom.xml中添加依赖
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring.security.version}</version>
</dependency>
对应jsp页面中导入
<%@taglib uri="http://www.springframework.org/security/tags" prefix="security"%>
常用标签介绍
① authentication
<security:authentication property="" htmlEscape="" scope="" var=""/>

② authorize
authorize是用来判断普通权限的,通过判断用户是否具有对应的权限而控制其所包含内容的显示
<security:authorize access="" method="" url="" var=""></security:authorize>

③ accesscontrollist
accesscontrollist标签是用于鉴定ACL权限的。其一共定义了三个属性:hasPermission、domainObject和var, 其中前两个是必须指定的
<security:accesscontrollist hasPermission="" domainObject="" var=""></security:accesscontrollist>

整理者:长路 时间:2020/10/28




