【转】Spring_Security_3应用的11个步骤
1.Spring Security
11个步骤为应用程序添加安全防护
2.历史与现状
自2003年出现的Spring扩展插件Acegi Security发展而来。
目前最新 版本为3.x,已成为Spring的一部分。
为J2EE企业应用程序提供可靠的安全性服务。
3.Authentication vs. Authorization
区分概念验证与授权
验证
这 个用户是谁?
用户身份可靠吗?
授权
某用户A是否可以访问资源R
某用户A是否可以执行M操作
某用户A是否可以对资 源R执行M操作
4.SS中的验证特点
支持多种验证方式
支持多种加密格式
支持组件的扩展和替换
可以本地化 输出信息
5.SS中的授权特点
支持多种仲裁方式
支持组件的扩展和替换
支持对页面访问、方法访问、对象访问 的授权。
6.SS核心安全实现
Web安全
通过配置Servlet Filter激活SS中的过滤器链
实现 Session一致性验证
实现免登陆验证(Remember-Me验证)
提供一系列标签库进行页面元素的安全控制
方法安全
通 过AOP模式实现安全代理
Web安全与方法安全均可以使用表达式语言定义访问规则
7.配置SS
配置Web.xml,应用安全过滤器
配置Spring,验证与授权部分
在web页面 中获取用户身份
在web页面中应用安全标签库
实现方法级安全
8.配置web.xml
<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> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
<?xml version="1.0" encoding="UTF-8"?> <beans:beansxmlns="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-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd"> </beans:beans>
<http auto-config="true"> <intercept-url pattern="/**" access="ROLE_USER" /> </http> <authentication-manager> <authentication-provider> <user-service> <user name="tom" password="123" authorities="ROLE_USER, ROLE_A" /> <user name="jerry" password="123" authorities="ROLE_USER, ROLE_B" /> </user-service> </authentication-provider> </authentication-manager>
<authentication-manager> <authentication-provider> <password-encoder hash=“md5”/> <jdbc-user-service data-source-ref="dataSource"/> </authentication-provider> </authentication-manager>
<http auto-config="true"> <intercept-url pattern="/js/**" filters="none"/> <intercept-url pattern="/css/**" filters="none"/> <intercept-url pattern="/images/**" filters="none"/> <intercept-url pattern="/a.jsp" access="ROLE_A" /> <intercept-url pattern="/b.jsp" access="ROLE_B" /> <intercept-url pattern="/c.jsp" access="ROLE_A, ROLE_B" /> <intercept-url pattern="/**" access="ROLE_USER" /> </http>
<!-- 指 定登陆页面、成功页面、失败页面--> <form-login login-page="/login.jsp" default-target-url="/index.jsp" authentication-failure-url="/login.jsp" /> <!-- 尝 试访问没有权限的页面时跳转的页面 --> <access-denied-handler error-page="/accessDenied.jsp"/> <!-- 使 用记住用户名、密码功能,指定数据源和加密的key --> <remember-me data-source-ref="dataSource" /> <!-- logout 页面,logout后清除session --> <logout invalidate-session="true" logout-success-url="/login.jsp" /> <!-- session 失 效后跳转的页面,最大登陆次数 --> <session-management invalid-session-url="/sessionTimeout.htm"> <concurrency-control max-sessions="1" expired-url="/sessionTimeout.htm" /> </session-management> </http>
<!-- 加载错误信息资源文件 --> <beans:bean id="messageSource" value="classpath:messages"/> </beans:bean>
Authentication auth = SecurityContextHolder.getContext().getAuthentication(); Collection<GrantedAuthority> col = auth.getAuthorities();
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> <sec:authentication property="name“/> <sec:authentication property="authorities“/>
<sec:authorizeifAnyGranted="ROLE_A"> <a href="a.jsp">你可以访问a.jsp</a> </sec:authorize> <sec:authorizeifNotGranted="ROLE_A"> 你不可以访问a.jsp </sec:authorize>
<sec:authorizeurl="/a.jsp"> <a href="a.jsp">你可以访问a.jsp</a> </sec:authorize>
<global-method-security pre-post-annotations="enabled"> <protect-pointcut expression="execution(* com.xasxt.*Service.add*(..))" access="ROLE_A"/> <protect-pointcut expression="execution(* com.xasxt.*Service.delete*(..))" access="ROLE_B"/> </global-method-security>
public class DemoService { @PreAuthorize("hasRole('ROLE_A')") public void methodA() { } @PreAuthorize("hasAnyRole('ROLE_A, ROLE_B')") public void methodB() { } } <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext*.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>login.jsp</welcome-file> </welcome-file-list> </web-app>
<?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-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd"> <http access-denied-page="/403.jsp"><!-- 当访问被拒绝时,会转到403.jsp --> <intercept-url pattern="/login.jsp" filters="none" /> <form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?error=true" default-target-url="/index.jsp" /> <logout logout-success-url="/login.jsp" /> <http-basic /> <!-- 增加一个filter,这点与Acegi是不一样的,不能修改默认的filter了,这个filter位于FILTER_SECURITY_INTERCEPTOR之前 --> <custom-filter before="FILTER_SECURITY_INTERCEPTOR" ref="myFilter" /> </http> <!-- 一个自定义的filter,必须包含authenticationManager,accessDecisionManager,securityMetadataSource三个属性, 我们的所有控制将在这三个类中实现,解释详见具体配置 --> <beans:bean id="myFilter" /> <beans:property name="accessDecisionManager" ref="myAccessDecisionManagerBean" /> <beans:property name="securityMetadataSource" ref="securityMetadataSource" /> </beans:bean> <!-- 认证管理器,实现用户认证的入口,主要实现UserDetailsService接口即可 --> <authentication-manager alias="authenticationManager"> <authentication-provider user-service-ref="myUserDetailService"> <!-- 如果用户的密码采用加密的话,可以加点“盐” <password-encoder hash="md5" /> --> </authentication-provider> </authentication-manager> <beans:bean id="myUserDetailService" /> <!-- 访问决策器,决定某个用户具有的角色,是否有足够的权限去访问某个资源 --> <beans:bean id="myAccessDecisionManagerBean" /> </beans:beans>
package com.robin.erp.fwk.security; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.springframework.security.access.SecurityMetadataSource; import org.springframework.security.access.intercept.AbstractSecurityInterceptor; import org.springframework.security.access.intercept.InterceptorStatusToken; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; public class MyFilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter { private FilterInvocationSecurityMetadataSource securityMetadataSource; // ~ Methods // ======================================================================================================== /** * Method that is actually called by the filter chain. Simply delegates to * the {@link #invoke(FilterInvocation)} method. * * @param request * the servlet request * @param response * the servlet response * @param chain * the filter chain * * @throws IOException * if the filter chain fails * @throws ServletException * if the filter chain fails */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { FilterInvocation fi = new FilterInvocation(request, response, chain); invoke(fi); } public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() { return this.securityMetadataSource; } public Class<? extends Object> getSecureObjectClass() { return FilterInvocation.class; } public void invoke(FilterInvocation fi) throws IOException, ServletException { InterceptorStatusToken token = super.beforeInvocation(fi); try { fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); } finally { super.afterInvocation(token, null); } } public SecurityMetadataSource obtainSecurityMetadataSource() { return this.securityMetadataSource; } public void setSecurityMetadataSource( FilterInvocationSecurityMetadataSource newSource) { this.securityMetadataSource = newSource; } @Override public void destroy() { } @Override public void init(FilterConfig arg0) throws ServletException { }package com.robin.erp.fwk.security; import java.util.ArrayList; import java.util.Collection; import org.springframework.dao.DataAccessException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.GrantedAuthorityImpl; 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; public class MyUserDetailService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { Collection<GrantedAuthority> auths=new ArrayList<GrantedAuthority>(); GrantedAuthorityImpl auth2=new GrantedAuthorityImpl("ROLE_ADMIN"); auths.add(auth2); if(username.equals("robin1")){ auths=new ArrayList<GrantedAuthority>(); GrantedAuthorityImpl auth1=new GrantedAuthorityImpl("ROLE_ROBIN"); auths.add(auth1); } // User(String username, String password, boolean enabled, boolean accountNonExpired, // boolean credentialsNonExpired, boolean accountNonLocked, Collection<GrantedAuthority> authorities) { User user = new User(username, "robin", true, true, true, true, auths); return user; } } package com.robin.erp.fwk.security; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; import org.springframework.security.web.util.AntUrlPathMatcher; import org.springframework.security.web.util.UrlMatcher; /** * * 此类在初始化时,应该取到所有资源及其对应角色的定义 * * @author Robin * */ public class MyInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource { private UrlMatcher urlMatcher = new AntUrlPathMatcher();; private static Map<String, Collection<ConfigAttribute>> resourceMap = null; public MyInvocationSecurityMetadataSource() { loadResourceDefine(); } private void loadResourceDefine() { resourceMap = new HashMap<String, Collection<ConfigAttribute>>(); Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>(); ConfigAttribute ca = new SecurityConfig("ROLE_ADMIN"); atts.add(ca); resourceMap.put("/index.jsp", atts); resourceMap.put("/i.jsp", atts); } // According to a URL, Find out permission configuration of this URL. public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException { // guess object is a URL. String url = ((FilterInvocation)object).getRequestUrl(); Iterator<String> ite = resourceMap.keySet().iterator(); while (ite.hasNext()) { String resURL = ite.next(); if (urlMatcher.pathMatchesUrl(url, resURL)) { return resourceMap.get(resURL); } } return null; } public boolean supports(Class<?> clazz) { return true; } public Collection<ConfigAttribute> getAllConfigAttributes() { return null; } } package com.robin.erp.fwk.security; import java.util.Collection; import java.util.Iterator; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.authentication.InsufficientAuthenticationException; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; public class MyAccessDecisionManager implements AccessDecisionManager { //In this method, need to compare authentication with configAttributes. // 1, A object is a URL, a filter was find permission configuration by this URL, and pass to here. // 2, Check authentication has attribute in permission configuration (configAttributes) // 3, If not match corresponding authentication, throw a AccessDeniedException. public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { if(configAttributes == null){ return ; } System.out.println(object.toString()); //object is a URL. Iterator<ConfigAttribute> ite=configAttributes.iterator(); while(ite.hasNext()){ ConfigAttribute ca=ite.next(); String needRole=((SecurityConfig)ca).getAttribute(); for(GrantedAuthority ga:authentication.getAuthorities()){ if(needRole.equals(ga.getAuthority())){ //ga is user's role. return; } } } throw new AccessDeniedException("no right"); } @Override public boolean supports(ConfigAttribute attribute) { // TODO Auto-generated method stub return true; } @Override public boolean supports(Class<?> clazz) { return true; } }