原文:Spring Security 3.x完整入门配置教程及其代码下载
源代码下载地址:http://www.zuidaima.com/share/1751865719933952.htm
Spring Security 3.x 出来一段时间了,跟Acegi是大不同了,与2.x的版本也有一些小小的区别,网上有一些文档,也有人翻译Spring Security 3.x的guide,但通过阅读guide,无法马上就能很容易的实现一个完整的实例。
我花了点儿时间,根据以前的实战经验,整理了一份完整的入门教程,供需要的朋友们参考。
1,建一个web project,并导入所有需要的lib,这步就不多讲了。
2,配置web.xml,使用Spring的机制装载:
contextConfigLocation
classpath:applicationContext*.xml
org.springframework.web.context.ContextLoaderListener
springSecurityFilterChain
org.springframework.web.filter.DelegatingFilterProxy
springSecurityFilterChain
/*
login.jsp
这个文件中的内容我相信大家都很熟悉了,不再多说了。
2,来看看applicationContext-security.xml这个配置文件,关于Spring Security的配置均在其中:
3,来看看自定义filter的实现:
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 {
}
}
最核心的代码就是invoke方法中的InterceptorStatusToken token = super.beforeInvocation(fi);这一句,即在执行doFilter之前,进行权限的检查,而具体的实现已经交给accessDecisionManager了,下文中会讲述。
4,来看看authentication-provider的实现:
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 auths=newArrayList();
GrantedAuthorityImpl auth2=newGrantedAuthorityImpl("ROLE_ADMIN");
auths.add(auth2);
if(username.equals("robin1")){
auths=newArrayList();
GrantedAuthorityImpl auth1=newGrantedAuthorityImpl("ROLE_ROBIN");
auths.add(auth1);
}
// User(String username, String password, boolean enabled, boolean accountNonExpired,
// boolean credentialsNonExpired, boolean accountNonLocked, Collection authorities) {
User user=new User(username,
"robin", true, true, true, true, auths);
return user;
}
}
在这个类中,你就可以从数据库中读入用户的密码,角色信息,是否锁定,账号是否过期等,我想这么简单的代码就不再多解释了。
5,对于资源的访问权限的定义,我们通过实现FilterInvocationSecurityMetadataSource这个接口来初始化数据。
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 > resourceMap= null ;
public MyInvocationSecurityMetadataSource() {
loadResourceDefine();
}
private void loadResourceDefine() {
resourceMap= new HashMap > ();
Collection atts= new ArrayList ();
ConfigAttribute ca= new SecurityConfig( " ROLE_ADMIN " );
atts.add(ca);
resourceMap.put( " /index.jsp " , atts);
resourceMap.put( " /i.jap " , atts);
}
// According to a URL, Find out permission configuration of this URL.
public Collection getAttributes(Object object)
throws IllegalArgumentException {
// guess object is a URL.
String url= ((FilterInvocation)object).getRequestUrl();
Iterator 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 getAllConfigAttributes() {
return null ;
}
}
看看loadResourceDefine方法,我在这里,假定index.jsp和i.jsp这两个资源,需要ROLE_ADMIN角色的用户才能访问。
这个类中,还有一个最核心的地方,就是提供某个资源对应的权限定义,即getAttributes方法返回的结果。注意,我例子中使用的是AntUrlPathMatcher这个path matcher来检查URL是否与资源定义匹配,事实上你还要用正则的方式来匹配,或者自己实现一个matcher。
6,剩下的就是最终的决策了,make a decision,其实也很容易,呵呵。
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 configAttributes)
throws AccessDeniedException, InsufficientAuthenticationException {
if(configAttributes==null){
return ;
}
System.out.println(object.toString()); //object is a URL.
Iterator 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;
}
}
在这个类中,最重要的是decide方法,如果不存在对该资源的定义,直接放行;否则,如果找到正确的角色,即认为拥有权限,并放行,否则throw new AccessDeniedException("no right");这样,就会进入上面提到的403.jsp页面。