优质博文:IT-BLOG-CN
一、Spring Security 简介
Spring Security
是一个能够为基于Spring
的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring
应用上下文中配置的 Bean,充分利用了Spring IoC
,DI
(控制反转 Inversion of Control
,DI
:Dependency Injection
依赖注入)和AOP
(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。
二、Spring Security 入门Demo
【1】创建Maven
工程(war
形式):spring-security-demo
【2】修改pom.xml
目录,如下:
<!-- 集中定义依赖版本号 -->
<properties><junit.version>4.12</junit.version><spring.version>4.2.4.RELEASE</spring.version><pagehelper.version>4.0.0</pagehelper.version><servlet-api.version>2.5</servlet-api.version><dubbo.version>2.8.4</dubbo.version><zookeeper.version>3.4.7</zookeeper.version><zkclient.version>0.1</zkclient.version> <mybatis.version>3.2.8</mybatis.version><mybatis.spring.version>1.2.2</mybatis.spring.version><mybatis.paginator.version>1.2.15</mybatis.paginator.version><mysql.version>5.1.32</mysql.version> <druid.version>1.0.9</druid.version><commons-fileupload.version>1.3.1</commons-fileupload.version><freemarker.version>2.3.23</freemarker.version><activemq.version>5.11.2</activemq.version><security.version>3.2.3.RELEASE</security.version> <solrj.version>4.10.3</solrj.version><ik.version>2012_u6</ik.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>
注意:如果只是给自己的项目中嵌入Spring Security
安全框架,只需要添加如下两个jar
包即可。
<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>
【3】创建web.xml
文件(通过Spring Security
拦截需要处理的请求和引入Spring Security
的配置文件)。
<?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"> <!-- 引入spring-security框架的配置文件 --><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><!-- 通过spring-security 内置的拦截器 springSecurityFilterChain 拦截 /* 的请求,名称不能修改,安全框架的入口配置 --><!-- 所有的请求通过拦截器(DelegatingFilterProxy)拦截后,找名为 springSecurityFilterChain 类进行逻辑处理,此类是spring security安全框架中所包含的类 --><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>
【4】创建Spring Security
配置文件:spring-security.xml
(与 web.xml
中引入的配置文件对应),代码中有配置的详细说明注解。
<?xml version="1.0" encoding="UTF-8"?>
<!-- 此配置将Spring Seucrity设置成了默认标签,其他使用时,需要添加如下前缀beans或dubbo等 -->
<beans:beansxmlns="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.xsdhttp://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsdhttp://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"><!-- 登录页面不能拦截 none任何角色都可访问如果你没有设置登录页security="none" ,将会出现以下错误 :"重定向次数过多"因为登录页会被反复重定向--><http pattern="/*.html" security="none"></http><http pattern="/css/**" security="none"></http><http pattern="/img/**" security="none"></http><http pattern="/js/**" security="none"></http><http pattern="/plugins/**" security="none"></http><!-- 注意:如果是用户申请登录名的请求也不能拦截 --><http pattern="/seller/add.do" security="none"></http><!-- 拦截页面 --><!-- use-expressions -为是否使用 Spring 表达式语言( SpEL ),默认为true ,如果开启,则拦截的配置应该写成以下形式<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />--><http use-expressions="false"><!-- /* 表示的是该目录下的资源,只包括本级目录不包括下级目录/** 表示的是该目录以及该目录下所有级别子目录的资源--><intercept-url pattern="/**" access="ROLE_SELLER" /><!-- form-login:开启表单登录,默认登录请求/login可以通过配置修改默认请求always-use-default-target:指定了是否在身份验证通过后总是跳转到default-target-url属性指定的URL。authentication-failure-url:登录失败,跳转页面 --><form-login login-page="/login.html"default-target-url="/index.html"authentication-failure-url="/login_error.html"always-use-default-target="true" /><!-- csrf disabled="true" 关闭csrf ,如果不加会出现错403 这种一般会自动生成在请求头信息中:'X-CSRF-TOKEN'(相当于一个校徽)防止跨站点攻击,但只能jsp实现,html不能实现,因此需要关闭此功能 CSRF(Cross-site request forgery)跨站请求伪造,也被称为“One Click Attack”或者Session Riding,通常缩写为CSRF或者XSRF,是一种对网站的恶意利用。--><csrf disabled="true" /><!-- 当页面中存在嵌入式iframe时,需要配置hears --><headers><frame-options policy="SAMEORIGIN" /></headers><!-- 登出,页面只需要发送/logout请求就可会触发 也可以修改默认的处理,例如logout-url=""可以修改登出的请求--><logout /></http><!-- Spring Security中 用户登录时认证管理器 --><!-- Spring Security是如何完成身份认证的?①、用户名和密码被过滤器获取到,封装成Authentication,通常情况下是UsernamePasswordAuthenticationToken这个实现类。②、AuthenticationManager 身份管理器负责验证这个Authentication。③、认证成功后,AuthenticationManager身份管理器返回一个被填充满了信息的(包括上面提到的权限信息,身份信息,细节信息,但密码通常会被移除)Authentication实例。④、SecurityContextHolder安全上下文容器将第3步填充了信息的Authentication,通过SecurityContextHolder.getContext().setAuthentication(…)方法,设置到其中。 --><authentication-manager><!-- user-service-ref 指向用户认证业务处理类,需要实现UserDetailsService接口--><!-- 如果测试,不想从数据库中获取用户,可以直接配置一个用户名和密码 ,特换掉如下authentication-provider内的配置即可。 --><authentication-provider><user-service><user name="admin" password="123456" authorities="ROLE_USER"/></user-service></authentication-provider><!-- <authentication-provider user-service-ref="userDetailServiceImpl">对密码进行bcrypt加密,比较时需要解密后处理,bcrypt与MD5不同,MD5加密后相同的密码生成相同的16位字符创,bcrybt相同的密码加密后生成不同的30位字符串,相当于MD5+盐<password-encoder hash="bcrypt"></password-encoder></authentication-provider> --></authentication-manager><!-- <beans:bean id="userDetailServiceImpl" class="com.pinyougou.shop.service.UserDetailServiceImpl">当自己的项目需要使用另一个项目中的服务类时 ,需要通过dubbo引入项目 dubbo标签<beans:property name="sellerService" ref="sellerService"></beans:property></beans:bean> --><!-- 引用dubbo sellerService服务:供登录用户业务处理类使用 --><!-- <dubbo:application name="pinyougou-shop-web" /><dubbo:registry address="zookeeper://192.168.159.129:2181" /><dubbo:reference id="sellerService"interface="com.pinyougou.sellergoods.service.SellerService"></dubbo:reference> -->
</beans:beans>
【5】需要自己创建:login.html
(登录页面 如下)、index.html
(登录成功跳转页面)、login_error.html
(登录失败跳转页面)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登陆</title>
</head>
<body>--欢迎登陆我的系统--<form action="/login" method="post">用户名:<input name="username"><br>密码:<input name="password"><br><button>登陆</button></form>
</body>
</html>
三、项目实战中,后台业务逻辑实现重要代码摘取,供实战中使用
【1】配置文件中配置的,登录时用户名和密码的业务逻辑处理类(实现UserDetailsService
:框架自带的接口),注意:普通demo
不需要此部分,主要用于真是环境登录逻辑的处理。
public class UserDetailServiceImpl implements UserDetailsService {//当通过配置文件的形式,引入服务类时需要设置set方法。private SellerService sellerService;public void setSellerService(SellerService sellerService) {this.sellerService = sellerService;}@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {//GrantedAuthority : 定义用户角色,需要实现的接口List<GrantedAuthority> list =new ArrayList<>();//用户添加角色,SimpleGrantedAuthority可以定义用户角色,实现了GrantedAuthority接口,//格式必须以(ROLE_)开头list.add(new SimpleGrantedAuthority("ROLE_SELLER"));//从数据库中获取用户信息。TbSeller seller = sellerService.findOne(username);if(seller != null) {//返回username:传过来的参数。seller.getPassword:数据库中获取到的用户密码。//list:用户的所有角色,可以从数据库中获取return new User(username, seller.getPassword(), list);}else {return null;}}
}
【2】BCrypt
加密过程(配置中说明了BCrypt
与MD5
的区别)。
@RequestMapping("/add")
public Result add(@RequestBody TbSeller seller){try {//BCrypt加密使用的对象BCryptPasswordEncoderBCryptPasswordEncoder cryptPasswordEncoder = new BCryptPasswordEncoder();//使用encode方法对传入的密码加密,返回30位的字符串String encode = cryptPasswordEncoder.encode(seller.getPassword());//业务处理:接入对象中seller.setPassword(encode);//调用服务层,入库sellerService.add(seller);return new Result(true, "增加成功");} catch (Exception e) {e.printStackTrace();return new Result(false, "增加失败");}
}
四、当程序中需要用户名时,可通过 SecurityContextHolder 对象获取
☏ SecurityContextHolder
用于存储安全上下文security context
的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保存在SecurityContextHolder
中。SecurityContextHolder
默认使用ThreadLocal
策略来存储认证信息。看到ThreadLocal
也就意味着,这是一种与线程绑定的策略。Spring Security
在用户登录时自动绑定认证信息到当前线程,在用户退出时,自动清除当前线程的认证信息。但这一切的前提,是你在web
场景下使用Spring Security
。
☏ 因为身份信息是与线程绑定的,所以可以在程序的任何地方使用静态方法获取用户信息。一个典型的获取当前登录用户的姓名的例子如下所示:getAuthentication()
返回了认证信息。
@RequestMapping("/name")
public Map<String, String> getName(){//获取登录名String name = SecurityContextHolder.getContext().getAuthentication().getName();Map<String, String> map = new HashMap<>();map.put("loginName", name);return map;
}
☏ Authentication
源码:
package org.springframework.security.core;// <1>
public interface Authentication extends Principal, Serializable { // <1>Collection<? extends GrantedAuthority> getAuthorities(); // <2>Object getCredentials();// <2>Object getDetails();// <2>Object getPrincipal();// <2>boolean isAuthenticated();// <2>void setAuthenticated(boolean var1) throws IllegalArgumentException;
}
【1】Authentication
是Spring Security
包中的接口,直接继承自Principal
类,而Principal
是位于java.security
包中的。可以见得,Authentication
在Spring Security
中是最高级别的身份/认证的抽象。
【2】由这个顶级接口,我们可以得到用户拥有的权限信息列表,密码,用户细节信息,用户身份信息,认证信息。
authentication.getPrincipal()
返回了一个 Object,我们将Principal
强转成了Spring Security
中最常用的UserDetails
,这在Spring Security
中非常常见,接口返回Object
,使用instanceof
判断类型,强转成对应的具体实现类。接口详细解读如下:
● getAuthorities()
:权限信息列表,默认是GrantedAuthority
接口的一些实现类,通常是代表权限信息的一系列字符串。
● getCredentials()
:密码信息,用户输入的密码字符串,在认证过后通常会被移除,用于保障安全。
● getDetails()
:细节信息,web
应用中的实现接口通常为WebAuthenticationDetails
,它记录了访问者的ip
地址和sessionId
的值。
● getPrincipal()
:最重要的身份信息,大部分情况下返回的是UserDetails
接口的实现类,也是框架中的常用接口之一。