---
title: "Spring Security 3应用的11个步骤"
author: "zwh910621"
date: "2010-12-30T10:27:09Z"
tags: []
categories: ["企业架构"]
slug: "spring-security-3-11"
draft: false
lastmod: "2010-12-30T10:27:09Z"
id: 855517
url: "https://javaheart88.iteye.com/blog/855517"
---

01. **Spring Security**   
    11个步骤为应用程序添加安全防护
02. **历史与现状**   
    自2003年出现的Spring扩展插件Acegi Security发展而来。  
    目前最新版本为3.x，已成为Spring的一部分。  
    为J2EE企业应用程序提供可靠的安全性服务。
03. **Authentication vs. Authorization**   
    区分概念验证与授权  
    验证  
    这个用户是谁？  
    用户身份可靠吗？  
    授权  
    某用户A是否可以访问资源R  
    某用户A是否可以执行M操作  
    某用户A是否可以对资源R执行M操作
04. **SS中的验证特点**   
    支持多种验证方式  
    支持多种加密格式  
    支持组件的扩展和替换  
    可以本地化输出信息
05. **SS中的授权特点**   
    支持多种仲裁方式  
    支持组件的扩展和替换  
    支持对页面访问、方法访问、对象访问的授权。
06. **SS核心安全实现**   
    Web安全  
    通过配置Servlet Filter激活SS中的过滤器链  
    实现Session一致性验证  
    实现免登陆验证（Remember-Me验证）  
    提供一系列标签库进行页面元素的安全控制  
    方法安全  
    通过AOP模式实现安全代理  
    Web安全与方法安全均可以使用表达式语言定义访问规则
07. **配置SS**   
    配置Web.xml，应用安全过滤器  
    配置Spring，验证与授权部分  
    在web页面中获取用户身份  
    在web页面中应用安全标签库  
    实现方法级安全
08. **1：配置web.xml** 
    
    Java代码
    
    01. &lt;filter&gt;
    02. &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
    03. &lt;filter- class &gt;org.springframework.web.filter.DelegatingFilterProxy&lt;/filter- class &gt;
    04. &lt;/filter&gt;
    05. &lt;filter-mapping&gt;
    06. &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
    07. &lt;url-pattern&gt;/\*&lt;/url-pattern&gt;
    08. &lt;/filter-mapping&gt;
    09. &lt;context-param&gt;
    10. &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
    11. &lt;param-value&gt;classpath:spring.xml&lt;/param-value&gt;
    12. &lt;/context-param&gt;
    13. &lt;listener&gt;
    14. &lt;listener- class &gt;
    15. org.springframework.web.context.ContextLoaderListener
    16. &lt;/listener- class &gt;
    17. &lt;/listener&gt;
09. **2：Spring配置文件中设置命名空间** 
    
    Java代码
    
    1. &lt;?xml version= "1.0"  encoding= "UTF-8" ?&gt;
    2. &lt;beans:beansxmlns= "http://www.springframework.org/schema/security"
    3. xmlns:beans= "http://www.springframework.org/schema/beans"  xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http: //www.springframework.org/schema/beans
    5. http: //www.springframework.org/schema/beans/spring-beans-3.0.xsd
    6. http: //www.springframework.org/schema/security
    7. http: //www.springframework.org/schema/security/spring-security-3.0.xsd"&gt;
    8. &lt;/beans:beans&gt;
10. **3：配置最基本的验证与授权** 
    
    Java代码
    
    01. &lt;http auto-config= "true" &gt;
    02. &lt;intercept-url pattern= "/\*\*"  access= "ROLE\_USER"  /&gt;
    03. &lt;/http&gt;
    04. &lt;authentication-manager&gt;
    05. &lt;authentication-provider&gt;
    06. &lt;user-service&gt;
    07. &lt;user name= "tom"  password= "123"  authorities= "ROLE\_USER, ROLE\_A"  /&gt;
    08. &lt;user name= "jerry"  password= "123"  authorities= "ROLE\_USER, ROLE\_B"  /&gt;
    09. &lt;/user-service&gt;
    10. &lt;/authentication-provider&gt;
    11. &lt;/authentication-manager&gt;
11. **4：通过数据库验证用户身份** 
    
    Java代码
    
    1. &lt;authentication-manager&gt;
    2. &lt;authentication-provider&gt;
    3. &lt;password-encoder hash=“md5”/&gt;
    4. &lt;jdbc-user-service data-source-ref= "dataSource" /&gt;
    5. &lt;/authentication-provider&gt;
    6. &lt;/authentication-manager&gt;
    7. 数据表结构见SS说明手册附录A
12. **5：完善web页面验证规则** 
    
    Java代码
    
    1. &lt;http auto-config= "true" &gt;
    2. &lt;intercept-url pattern= "/js/\*\*"  filters= "none" /&gt;
    3. &lt;intercept-url pattern= "/css/\*\*"  filters= "none" /&gt;
    4. &lt;intercept-url pattern= "/images/\*\*"  filters= "none" /&gt;
    5. &lt;intercept-url pattern= "/a.jsp"  access= "ROLE\_A"  /&gt;
    6. &lt;intercept-url pattern= "/b.jsp"  access= "ROLE\_B"  /&gt;
    7. &lt;intercept-url pattern= "/c.jsp"  access= "ROLE\_A, ROLE\_B"  /&gt;
    8. &lt;intercept-url pattern= "/\*\*"  access= "ROLE\_USER"  /&gt;
    9. &lt;/http&gt;
13. **6：自定义验证配置** 
    
    Java代码
    
    01. &lt;http auto-config= "true" &gt;
    02. &lt;!-- 指定登陆页面、成功页面、失败页面--&gt;
    03. &lt;form-login login-page= "/login.jsp"   default -target-url= "/index.jsp"  authentication-failure-url= "/login.jsp"  /&gt;
    04. &lt;!-- 尝试访问没有权限的页面时跳转的页面 --&gt;
    05. &lt;access-denied-handler error-page= "/accessDenied.jsp" /&gt;
    06. &lt;!-- 使用记住用户名、密码功能，指定数据源和加密的key --&gt;
    07. &lt;remember-me data-source-ref= "dataSource"  /&gt;
    08. &lt;!-- logout页面，logout后清除session --&gt;
    09. &lt;logout invalidate-session= "true"  logout-success-url= "/login.jsp"  /&gt;
    10. &lt;!-- session 失效后跳转的页面，最大登陆次数 --&gt;
    11. &lt;session-management invalid-session-url= "/sessionTimeout.htm" &gt;
    12. &lt;concurrency-control max-sessions= "1"  expired-url= "/sessionTimeout.htm"  /&gt;
    13. &lt;/session-management&gt;
    14. &lt;/http&gt;
    15. 可以使用SS自带的登陆页面作为login.jsp的模板
14. **7：本地化消息输出**   
    拷贝本地化资源文件后，在配置文件中加载该文件：
    
    Java代码
    
    1. &lt;!-- 加载错误信息资源文件 --&gt;
    2. &lt;beans:bean id= "messageSource"
    3. class = "org.springframework.context.support.ReloadableResourceBundleMessageSource" &gt;
    4. &lt;beans:property name= "basename"  value= "classpath:messages" /&gt;
    5. &lt;/beans:bean&gt;
    6. 资源文件在SS核心包：spring-security-core- 3.0 . 2 .RELEASE.jar的orgspringframeworksecurity目录中
15. **8：在web页面中获取用户信息** 
    
    Java代码
    
    1. 方式一：Java代码
    2. Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    3. Collection&lt;GrantedAuthority&gt; col = auth.getAuthorities();
    4. 方式二：标签库
    5. &lt;%@ taglib prefix= "sec"  uri= "http://www.springframework.org/security/tags"  %&gt;
    6. &lt;sec:authentication property="name“/&gt;
    7. &lt;sec:authentication property="authorities“/&gt;
16. **9：在web页面进行元素安全控制** 
    
    Java代码
    
    01. 方式一
    02. &lt;sec:authorizeifAnyGranted= "ROLE\_A" &gt;
    03. &lt;a href= "a.jsp" &gt;你可以访问a.jsp&lt;/a&gt;
    04. &lt;/sec:authorize&gt;
    05. &lt;sec:authorizeifNotGranted= "ROLE\_A" &gt;
    06. 你不可以访问a.jsp
    07. &lt;/sec:authorize&gt;
    08. 方式二
    09. &lt;sec:authorizeurl= "/a.jsp" &gt;
    10. &lt;a href= "a.jsp" &gt;你可以访问a.jsp&lt;/a&gt;
    11. &lt;/sec:authorize&gt;
17. **10：全局方法安全控制** 
    
    Java代码
    
    1. &lt;global-method-security pre-post-annotations= "enabled" &gt;
    2. &lt;protect-pointcut expression= "execution(* com.xasxt.\*Service.add\*(..))"  access= "ROLE\_A" /&gt;
    3. &lt;protect-pointcut expression= "execution(* com.xasxt.\*Service.delete\*(..))"  access= "ROLE\_B" /&gt;
    4. &lt;/global-method-security&gt;
    5. 此处使用了AspectJ中常用的切入点表达式（百度：AspectJ execution）
18. **11：使用注解进行方法安全控制** 
    
    Java代码
    
    1. public   class  DemoService {
    2. @PreAuthorize ( "hasRole(&apos;ROLE\_A&apos;)" )
    3. public   void  methodA() {
    4. }
    5. @PreAuthorize ( "hasAnyRole(&apos;ROLE\_A, ROLE\_B&apos;)" )
    6. public   void  methodB() {
    7. }
    8. }
    9. hasRole与hasAnyRole为SS通用内置表达式（google : spring security Common Built-In Expressions）
19. **12：下一步做什么？？？**   
    采用更安全的验证方式  
    采用安全的数据传输方式  
    实现动态授权  
    自定义验证与授权部件  
    实现数据级安全