1. 简介
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。
2. 简单使用
2.1 依赖
SpringSecutiry依赖于spring,所以需要引入spring依赖
spring依赖
<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>
SpringSecutiry依赖
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
2.2 web.xml配置
<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>
注意:
1. 过滤器的名称springSecurityFilterChain是个固定值,不能更改
2. 过滤器类DelegatingFilterProxy只是一个过滤器代理类,真正干活的是springSecurityFilterChain。
3. 这个过滤器是整个SpringSecutiry框架的入口
4. spring-security.xml就是一个spring的配置文件,只是在其中配置了一些认证信息
2.3 spring-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="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.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
</beans:beans>
注意:
1. 该配置文件中的根元素不是我们熟悉的beans了,而是beans:beans,beans是spring默认的,且只能有一个是默认的,所以这里加了个前缀。
2. 在SpringSecutiry中的安全配置非常多,所以我们奖beansd的命名空间定义为<beans:beans xmlns="http://www.springframework.org/schema/security",这样如果要在SpringSecutiry中定义安全安全标签就可以直接定义了
例如:<http use-expressions="false"></http>
2.3.1 使用<http>配置页面拦截规则
1)http标签的属性
1. use-expressions:是否启动SPell表达式,默认值是true
2. security:是否安全配置。none表示不用拦截,默认是true
2)http的子标签
1. intercept-url:拦截的请求路径
pattern :匹配路径。
/* 表示的是该目录下的资源,只包括本级目录不包括下级目录
/** 表示的是该目录以及该目录下所有级别子目录的资源
access:配置角色名称。注意:角色名称必须以ROLE_开头,后面的自定义
例如:表示当前用户必须有ROLE_USER的角色才允许访问根目录及其子目录下的所有文件
<intercept-url pattern="/**" access="ROLE_USER" />
注意:
(1)如果要这样配置需要将use-expressions设置为false,不起用SPEL表达式
(2) 如果不配置或者设置为false,需要使用SPEL表达式,例如:
<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
(3)如果访问规则比较简单,我们一般是关闭SPEL表达式的,如果访问规则比较复杂,往往需要打开SPEL表达式。
2. <form-login/>:开启表单登录功能
加上该标签,当系统没登录页面的时候,会自动生成一个登录页面,例如:
3. <csrf disabled="true"/>:关闭CSF
4. headers标签:头信息
如果页面中有ifram框架页,就需要在这里配置frame-options,例如:
<headers>
<!-- 配置框架也允许使用 -->
<frame-options policy="SAMEORIGIN"/>
</headers>
5. logout:退出登录
之前我们做退出登录需要清空session等,现在用了SpringSecutiry只需要加上一个<logout/>标签就可以了,默认情况下,SpringSecutiry会给我们自动生成一个退出登录的链接/logout
当然,该标签下有一些其他的属性
(1)logout-success-url:指定退出登录成功之后跳转的页面地址,默认是跳转到我们登录页面,如果不希望跳转到登录页面可以在这里配置跳转url。
(2)logout-url:指定退出url,默认url是/logout
2.3.2 <authentication-manager>认证管理器
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="123456" authorities="ROLE_USER"/>
</user-service>
</authentication-provider>
</authentication-manager>
1)<authentication-provider>认证提供者
2)<user-service> 用来配置当前系统登录用户
2)<user name="admin" password="123456" authorities="ROLE_USER"/>
name:表示用户名称
password:登录密码
authorities:用户所属角色
3. 入门案例
3.1 添加依赖
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bjc</groupId>
<artifactId>springSecurityDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<spring.version>4.2.4.RELEASE</spring.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>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</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.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<configuration>
<!-- 指定端口 -->
<port>9090</port>
<!-- 请求路径 -->
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
3.2 配置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://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<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>
</web-app>
3.3 新建index.html页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
welcome to springSecurity!
</body>
</html>
3.4 新建spring-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="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.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<!-- 页面拦截规则 -->
<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>
</beans:beans>
3.5 测试
1. 输入http://localhost:9090/index.html 如图,页面跳转到登录
2. 输入错误的用户名和密码
3. 重新输入正确的用户名和密码
4. 指定自定义登录页面
4.1 <form-login>标签
注意:自定义的登录页面login.html 的用户名和密码的name属性如果是username和password,form-login就不用配置username-parameter(用户名)和password-parameter(密码)
4.1.1 标签属性
1)login-page:指定登录页面。例如:login-page="/login.html"
注意:页面路径必须是/开头
2)default-target-url:指定了成功进行身份验证和授权后默认呈现给用户的页面。例如:login-processing-url=“/index.html”
3)authentication-failure-url:指定了身份验证失败时跳转到的页面。例如:authentication-failure-url=“/error.html”
4)login-processing-url:指定登录跳转连接。默认是/login。例如:login-processing-url=”/login2”
注意:login-processing-url的属性值与form表单的action的属性值保持一致。
5)username-parameter:用户名,属性值与form表单是用户名属性值保持一致,默认是username
6)password-parameter:密码,属性值与form表单的密码属性值保持一致,默认是password
7)always-use-default-target:设置登录之后,总是跳转到默认的页面。默认false
注意:对于后端管理系统,一般这个需要设置为true,前端系统不需要设置。设置这个的作用的是不会记忆上一次登录的url,而是只要登录了就会跳转到设置的默认登录成功之后跳转界面。
4.2 指定登录页面不拦截
因为/**拦截所有请求了,所以页面跳转到login.html的时候会出现“localhost将您重定向次数过多的错误”,所以,我们需要将登录页面排除掉
4.2.1 设置不过滤的页面
只需要在配置一个http拦截,拦截login.html,设置security="none",例如:
<http pattern="/login.html" security="none"></http>
注意:这种方式一般设置静态的HTML页面,象controller层的连接一般不采用这种方式来配置,因为该方式会跳过security的认证,导致,我们在后台使用SecurityContextHolder.getContext()获取用户名的时候报nullPoint异常。解决办法是采用匿名配置
4.2.2 匿名角色设置不过滤页面
在<http use-expressions="false">标签下添加如下配置
<intercept-url pattern="/cart/*.do" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
注意: access="IS_AUTHENTICATED_ANONYMOUSLY"表示使用匿名角色登录。
4.3 关闭csrf功能
在<form-login>标签下添加<csrf disabled="true"/> ,如果不加会报错
注意:CSRF(Cross-site request forgery)跨站请求伪造,也被称为“One Click Attack”或者Session Riding,通常缩写为CSRF或者XSRF,是一种对网站的恶意利用
完整的简单配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="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.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<!-- 页面拦截规则 -->
<http pattern="/login.html" security="none"></http>
<http use-expressions="false" >
<intercept-url pattern="/**" access="ROLE_USER" />
<form-login default-target-url="/index.html" login-page="/login.html"/>
<csrf disabled="true"/>
</http>
<!-- 认证管理器 -->
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="123456" authorities="ROLE_USER"/>
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
注意:自定义页面的form表单的action是/login,method是post。/login是框架自动生成的,默认值是/login例如:
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="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.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<!-- 页面拦截规则 -->
<!-- 1. 设置不拦截的请求 -->
<http pattern="/css/**" security="none"></http>
<http pattern="/js/**" security="none"></http>
<http pattern="/img/**" security="none"></http>
<http pattern="/plugins/**" security="none"></http>
<http pattern="/*.html" security="none"></http>
<http use-expressions="false" >
<!-- 当前用户必须拥有ROLE_ADMIN的角色才可以访问 -->
<intercept-url pattern="/**" access="ROLE_ADMIN" />
<form-login default-target-url="/admin/index.html" login-page="/login.html" authentication-failure-url="/login.html" always-use-default-target="true"/>
<csrf disabled="true"/>
<headers>
<frame-options policy="SAMEORIGIN"/>
</headers>
<logout/>
</http>
<!-- 认证管理器 -->
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="123456" authorities="ROLE_ADMIN"/>
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
4.3 SpringSecutiry后端代码
我们在后端可以通过SpringSecutiry提供的API进行一系列的操作,例如通过SecurityContextHolder获取上下文context从而得到登录用户名,例如:
import java.util.HashMap;
import java.util.Map;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/login")
public class LoginController {
@RequestMapping("/name")
public Map<String, Object> name(){
Map<String, Object> map = new HashMap<String, Object>();
// 获取登录用户名
String name = SecurityContextHolder.getContext().getAuthentication().getName();
map.put("loginName", name);
return map;
}
}
5. 动态认证
前面的认证用户是在配置文件中写死的,这种方式最简便,但是局限性太大,只适合那些用户量比较小的微型系统,SpringSecutiry中给我们提供了一种机制,就是通过实现UserDetailService接口的方式来自定义我们的认证类
操作步骤:
1)自定义认证类
实现UserDetailsService接口即可,例如;
package com.pinyougou.shop.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.pinyougou.pojo.TbSeller;
import com.pinyougou.sellergoods.service.SellerService;
/**
* 认证类
* @author Administrator
*
*/
public class UserDetailServiceImpl implements UserDetailsService{
// 注入SellerService,用户校验用户名和密码
private SellerService sellerService;
public void setSellerService(SellerService sellerService) {
this.sellerService = sellerService;
}
/*
* username 是用户登录的时候输入的用户名
* 返回null 就登录失败
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 获取角色组
List<GrantedAuthority> authorities = new ArrayList<>();
GrantedAuthority e = new SimpleGrantedAuthority("ROLE_SELLER");
authorities.add(e );
// 根据用户名查询对应的对象
TbSeller seller = sellerService.findOne(username);
if(null != seller){
if(seller.getStatus().equals("1")){ // 只有审核通过的用户才允许登录
// 认证
User user = new User(username, seller.getPassword(), authorities);
return user;
}
}
return null;
}
}
2)配置认证类,如图:
注意:因为我的案例是用的dubbox远程调用的服务,所以,这里不能直接注入,需要通过dubbox来注入
完整的配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
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://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<!-- 页面拦截规则 -->
<!-- 1. 设置不拦截的请求 -->
<http pattern="/css/**" security="none"></http>
<http pattern="/js/**" security="none"></http>
<http pattern="/img/**" security="none"></http>
<http pattern="/plugins/**" security="none"></http>
<http pattern="/*.html" security="none"></http>
<http pattern="/seller/add.do" security="none"></http>
<http use-expressions="false" >
<!-- 当前用户必须拥有ROLE_SELLER的角色才可以访问 -->
<intercept-url pattern="/**" access="ROLE_SELLER" />
<form-login default-target-url="/admin/index.html" login-page="/shoplogin.html" authentication-failure-url="/shoplogin.html"/>
<csrf disabled="true"/>
<headers>
<frame-options policy="SAMEORIGIN"/>
</headers>
<logout/>
</http>
<!-- 认证管理器 -->
<authentication-manager>
<authentication-provider user-service-ref="userDetailService">
</authentication-provider>
</authentication-manager>
<!-- 添加认证类 -->
<beans:bean id="userDetailService" class="com.pinyougou.shop.service.UserDetailServiceImpl">
<beans:property name="sellerService" ref="sellerService"></beans:property>
</beans:bean>
<!-- 引用dubbo 服务 -->
<dubbo:application name="pinyougou-manager-web" />
<dubbo:registry address="zookeeper://192.168.25.130:2181"/>
<!-- 远程注入sellerService -->
<dubbo:reference id="sellerService" interface="com.pinyougou.sellergoods.service.SellerService"></dubbo:reference>
</beans:beans>
6. SpringSecutiry的加密算法BCrypt
6.1 加密
SpringSecutiry中,给我们提供了一个类bCryptPasswordEncoder,我们可以很方便的对密码进行加密,其比Md5更安全,采用的是动态“盐”机制。
例如:
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
String encode = bCryptPasswordEncoder.encode(seller.getPassword());
seller.setPassword(encode);
6.2 解密
通过SpringSecutiry加密之后,要解密也相当的简单,只需要在配置文件中配置一下即可。
如图:
注意:解密类就是加密类