Spring Security 2 配置精讲
引用说明:原文来自于http://downpour.iteye.com/blog/319965,为了方便本人阅读,文本格式略有调整。
论坛上看了不少Spring Security的相关文章。这些文章基本上都还是基于Acegi-1.X的配置方式,而主要的配置示例也来自于SpringSide的贡献。
众所周知,SpringSecurity针对Acegi的一个重大的改进就在于其配置方式大大简化了。所以如果配置还是基于Acegi-1.X这样比较繁琐的配置方式的话,那么我们还不如直接使用Acegi而不要去升级了。所以在这里,我将结合一个示例,重点讨论一下SpringSecurity2是如何进行配置简化的。
搭建基础环境
首先我们为示例搭建基本的开发环境,环境的搭建方式,可以参考我的另外一篇文章:http://www.iteye.com/wiki/struts2/1321-struts2-development-environment-to-build
整个环境的搭建包括:创建合适的目录结构、加入了合适的Library,加入了基本的Jetty启动类、加入基本的配置文件等。最终的项目结构,可以参考我的附件。
参考文档
这里主要的参考文档是SpringSecurity的自带的Reference。网络上有一个它的中文翻译,地址如下:http://www.family168.com/tutorial/springsecurity/html/springsecurity.html
除此之外,springside有一个比较完整的例子,不过是基于Acegi的,我也参阅了其中的一些实现。
SpringSecurity基本配置
SpringSecurity是基于Spring的的权限认证框架,对于Spring和Acegi已经比较熟悉的同学对于之前的配置方式应该已经非常了解。接下来的例子,将向大家展示SpringSecurity基于schema的配置方式。
最小化配置
1.在web.xml文件中加入Filter声明
CREATE TABLE users ( username VARCHAR(50) NOT NULL PRIMARY KEY, password VARCHAR(50) NOT NULL, enabled BIT NOT NULL ); CREATE TABLE authorities ( username VARCHAR(50) NOT NULL, authority VARCHAR(50) NOT NULL );
不过这种设计方式在实际生产环境中基本上不会采用。一般来说,我们会使用逻辑主键ID来标示每个User和每个Authorities(Role)。而且从典型意义上讲,他们之间是一个多对多的关系,我们会采用3张表来表示,下面是我在MySQL中建立的3张表的schema示例:
CREATE TABLE `user` ( `id` int(11) NOT NULL auto_increment, `name` varchar(255) default NULL, `password` varchar(255) default NULL, `disabled` int(1) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `role` ( `id` int(11) NOT NULL auto_increment, `name` varchar(255) default NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `user_role` ( `user_id` int(11) NOT NULL, `role_id` int(11) NOT NULL, PRIMARY KEY (`user_id`,`role_id`), UNIQUE KEY `role_id` (`role_id`), KEY `FK143BF46AF6AD4381` (`user_id`), KEY `FK143BF46A51827FA1` (`role_id`), CONSTRAINT `FK143BF46A51827FA1` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`), CONSTRAINT `FK143BF46AF6AD4381` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
通过配置SQL来模拟用户和权限
有了数据库的表设计,我们就可以在SpringSecurity中,通过配置SQL,来模拟用户和权限,这依然通过<authentication-provider>来完成:
public interface UserDetails extends Serializable { GrantedAuthority[] getAuthorities(); String getPassword(); String getUsername(); boolean isAccountNonExpired(); boolean isAccountNonLocked(); boolean isCredentialsNonExpired(); boolean isEnabled(); }
public interface UserDetailsService { UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException; }
非常清楚,一个接口用于模拟用户,另外一个用于模拟读取用户的过程。所以我们可以通过实现这两个接口,来完成使用数据库对用户和权限进行管理的需求。在这里,我将给出一个使用Hibernate来定义用户和权限之间关系的示例。
1.定义User类和Role类,使他们之间形成多对多的关系
@Entity @Proxy(lazy = false) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class User { private static final long serialVersionUID = 8026813053768023527L; @Id @GeneratedValue private Integer id; private String name; private String password; private boolean disabled; @ManyToMany(targetEntity = Role.class, fetch = FetchType.EAGER) @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) private Set<Role> roles; // setters and getters }
@Entity @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Role { @Id @GeneratedValue private Integer id; private String name; // setters and getters }
请注意这里的Annotation的写法。同时,我为User和Role之间配置了缓存。并且将他们之间的关联关系设置的lazy属性设置成false,从而保证在User对象取出之后的使用不会因为脱离session的生命周期而产生lazyloading问题。
2.使User类实现UserDetails接口
接下来,我们让User类去实现UserDetails接口:
@Entity @Proxy(lazy = false) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class User implements UserDetails { private static final long serialVersionUID = 8026813053768023527L; @Id @GeneratedValue private Integer id; private String name; private String password; private boolean disabled; @ManyToMany(targetEntity = Role.class, fetch = FetchType.EAGER) @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) private Set<Role> roles; /** * The default constructor */ public User() { } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#getAuthorities() */ public GrantedAuthority[] getAuthorities() { List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(roles.size()); for(Role role : roles) { grantedAuthorities.add(new GrantedAuthorityImpl(role.getName())); } return grantedAuthorities.toArray(new GrantedAuthority[roles.size()]); } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#getPassword() */ public String getPassword() { return password; } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#getUsername() */ public String getUsername() { return name; } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#isAccountNonExpired() */ public boolean isAccountNonExpired() { return true; } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#isAccountNonLocked() */ public boolean isAccountNonLocked() { return true; } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#isCredentialsNonExpired() */ public boolean isCredentialsNonExpired() { return true; } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#isEnabled() */ public boolean isEnabled() { return !this.disabled; } // setters and getters }
实现UserDetails接口中的每个函数,其实没什么很大的难度,除了其中的一个函数我需要额外强调一下:
/* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#getAuthorities() */ public GrantedAuthority[] getAuthorities() { List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(roles.size()); for(Role role : roles) { grantedAuthorities.add(new GrantedAuthorityImpl(role.getName())); } return grantedAuthorities.toArray(new GrantedAuthority[roles.size()]); }
这个函数的实际作用是根据User返回这个User所拥有的权限列表。如果以上面曾经用过的例子来说,如果当前User是downpour,我需要得到ROLE_USER和ROLE_ADMIN;如果当前User是robbin,我需要得到ROLE_USER。
了解了含义,实现就变得简单了,由于User与Role是多对多的关系,我们可以通过User得到所有这个User所对应的Role,并把这些Role的name拼装起来返回。
由此可见,实现UserDetails接口,并没有什么神秘的地方,它只是实际上在一定程度上只是代替了使用配置文件的硬编码:
@Repository("securityManager") public class SecurityManagerSupport extends HibernateDaoSupport implements UserDetailsService { /** * Init sessionFactory here because the annotation of Spring 2.5 can not support override inject * * @param sessionFactory */ @Autowired public void init(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); } public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException { List<User> users = getHibernateTemplate().find("FROM User user WHERE user.name = ? AND user.disabled = false", userName); if(users.isEmpty()) { throw new UsernameNotFoundException("User " + userName + " has no GrantedAuthority"); } return users.get(0); } }
这个实现非常简单,由于我们的User对象已经实现了UserDetails接口。所以我们只要使用Hibernate,根据userName取出相应的User对象即可。注意在这里,由于我们对于User的关联对象Roles都设置了lazy="false",所以我们无需担心lazyloading的问题。
4.配置文件
有了上面的代码,一切都变得很简单,重新定义authentication-provider节点即可。如果你使用Spring2.5的Annotation配置功能,你甚至可以不需要在配置文件中定义securityManager的bean。
CREATE TABLE `role` ( `id` int(11) NOT NULL auto_increment, `name` varchar(255) default NULL, `description` varchar(255) default NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `resource` ( `id` int(11) NOT NULL auto_increment, `type` varchar(255) default NULL, `value` varchar(255) default NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `role_resource` ( `role_id` int(11) NOT NULL, `resource_id` int(11) NOT NULL, PRIMARY KEY (`role_id`,`resource_id`), KEY `FKAEE599B751827FA1` (`role_id`), KEY `FKAEE599B7EFD18D21` (`resource_id`), CONSTRAINT `FKAEE599B751827FA1` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`), CONSTRAINT `FKAEE599B7EFD18D21` FOREIGN KEY (`resource_id`) REFERENCES `resource` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
在这里Resource可能分成多种类型,比如MENU,URL,METHOD等等。
针对资源的认证
针对资源的认证,实际上应该由SpringSecurity中的FilterSecurityInterceptor这个过滤器来完成。不过内置的FilterSecurityInterceptor的实现往往无法满足我们的要求,所以传统的Acegi的方式,我们往往会替换FilterSecurityInterceptor的实现,从而对URL等资源进行认证。
不过在SpringSecurity中,由于默认的拦截器链内置了FilterSecurityInterceptor,而且上面我们也提到过,这个实现无法被替换。这就使我们犯了难。我们如何对资源进行认证呢?
实际上,我们虽然无法替换FilterSecurityInterceptor的默认实现,不过我们可以再实现一个类似的过滤器,并将我们自己的过滤器作为一个customer-filter,加到默认的过滤器链的最后,从而完成整个过滤检查。
接下来我们就来看看一个完整的例子:
1.建立权限(Role)和资源(Resource)之间的关联关系
修改上面的权限(Role)的Entity定义:
@Entity @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Role { @Id @GeneratedValue private Integer id; private String name; @ManyToMany(targetEntity = Resource.class, fetch = FetchType.EAGER) @JoinTable(name = "role_resource", joinColumns = @JoinColumn(name = "role_id"), inverseJoinColumns = @JoinColumn(name = "resource_id")) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) private Set<Resource> resources; // setters and getter }
增加资源(Resource)的Entity定义:
@Entity @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Resource { @Id @GeneratedValue private Integer id; private String type; private String value; @ManyToMany(mappedBy = "resources", targetEntity = Role.class, fetch = FetchType.EAGER) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) private Set<Role> roles; /** * The default constructor */ public Resource() { } }
注意他们之间的多对多关系,以及他们之间关联关系的缓存和lazy属性设置。
2.在系统启动的时候,把所有的资源load到内存作为缓存
由于资源信息对于每个项目来说,相对固定,所以我们可以将他们在系统启动的时候就load到内存作为缓存。这里做法很多,我给出的示例是将资源的存放在servletContext中。
public class ServletContextLoaderListener implements ServletContextListener { /* (non-Javadoc) * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) */ public void contextInitialized(ServletContextEvent servletContextEvent) { ServletContext servletContext = servletContextEvent.getServletContext(); SecurityManager securityManager = this.getSecurityManager(servletContext); Map<String, String> urlAuthorities = securityManager.loadUrlAuthorities(); servletContext.setAttribute("urlAuthorities", urlAuthorities); } /* (non-Javadoc) * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent) */ public void contextDestroyed(ServletContextEvent servletContextEvent) { servletContextEvent.getServletContext().removeAttribute("urlAuthorities"); } /** * Get SecurityManager from ApplicationContext * * @param servletContext * @return */ protected SecurityManager getSecurityManager(ServletContext servletContext) { return (SecurityManager) WebApplicationContextUtils.getWebApplicationContext(servletContext).getBean("securityManager"); } }
这里,我们看到了SecurityManager,这是一个接口,用于权限相关的逻辑处理。还记得之前我们使用数据库管理User的时候所使用的一个实现类SecurityManagerSupport嘛?我们不妨依然借用这个类,让它实现SecurityManager接口,来同时完成url的读取工作。
@Service("securityManager") public class SecurityManagerSupport extends HibernateDaoSupport implements UserDetailsService, SecurityManager { /** * Init sessionFactory here because the annotation of Spring 2.5 can not support override inject * * @param sessionFactory */ @Autowired public void init(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); } /* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) */ public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException { List<User> users = getHibernateTemplate().find("FROM User user WHERE user.name = ? AND user.disabled = false", userName); if(users.isEmpty()) { throw new UsernameNotFoundException("User " + userName + " has no GrantedAuthority"); } return users.get(0); } /* (non-Javadoc) * @see com.javaeye.sample.security.SecurityManager#loadUrlAuthorities() */ public Map<String, String> loadUrlAuthorities() { Map<String, String> urlAuthorities = new HashMap<String, String>(); List<Resource> urlResources = getHibernateTemplate().find("FROM Resource resource WHERE resource.type = ?", "URL"); for(Resource resource : urlResources) { urlAuthorities.put(resource.getValue(), resource.getRoleAuthorities()); } return urlAuthorities; } }
3.编写自己的FilterInvocationDefinitionSource实现类,对资源进行认证
public class SecureResourceFilterInvocationDefinitionSource implements FilterInvocationDefinitionSource, InitializingBean { private UrlMatcher urlMatcher; private boolean useAntPath = true; private boolean lowercaseComparisons = true; /** * @param useAntPath the useAntPath to set */ public void setUseAntPath(boolean useAntPath) { this.useAntPath = useAntPath; } /** * @param lowercaseComparisons */ public void setLowercaseComparisons(boolean lowercaseComparisons) { this.lowercaseComparisons = lowercaseComparisons; } /* (non-Javadoc) * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() */ public void afterPropertiesSet() throws Exception { // default url matcher will be RegexUrlPathMatcher this.urlMatcher = new RegexUrlPathMatcher(); if (useAntPath) { // change the implementation if required this.urlMatcher = new AntUrlPathMatcher(); } // Only change from the defaults if the attribute has been set if ("true".equals(lowercaseComparisons)) { if (!this.useAntPath) { ((RegexUrlPathMatcher) this.urlMatcher).setRequiresLowerCaseUrl(true); } } else if ("false".equals(lowercaseComparisons)) { if (this.useAntPath) { ((AntUrlPathMatcher) this.urlMatcher).setRequiresLowerCaseUrl(false); } } } /* (non-Javadoc) * @see org.springframework.security.intercept.ObjectDefinitionSource#getAttributes(java.lang.Object) */ public ConfigAttributeDefinition getAttributes(Object filter) throws IllegalArgumentException { FilterInvocation filterInvocation = (FilterInvocation) filter; String requestURI = filterInvocation.getRequestUrl(); Map<String, String> urlAuthorities = this.getUrlAuthorities(filterInvocation); String grantedAuthorities = null; for(Iterator<Map.Entry<String, String>> iter = urlAuthorities.entrySet().iterator(); iter.hasNext();) { Map.Entry<String, String> entry = iter.next(); String url = entry.getKey(); if(urlMatcher.pathMatchesUrl(url, requestURI)) { grantedAuthorities = entry.getValue(); break; } } if(grantedAuthorities != null) { ConfigAttributeEditor configAttrEditor = new ConfigAttributeEditor(); configAttrEditor.setAsText(grantedAuthorities); return (ConfigAttributeDefinition) configAttrEditor.getValue(); } return null; } /* (non-Javadoc) * @see org.springframework.security.intercept.ObjectDefinitionSource#getConfigAttributeDefinitions() */ @SuppressWarnings("unchecked") public Collection getConfigAttributeDefinitions() { return null; } /* (non-Javadoc) * @see org.springframework.security.intercept.ObjectDefinitionSource#supports(java.lang.Class) */ @SuppressWarnings("unchecked") public boolean supports(Class clazz) { return true; } /** * * @param filterInvocation * @return */ @SuppressWarnings("unchecked") private Map<String, String> getUrlAuthorities(FilterInvocation filterInvocation) { ServletContext servletContext = filterInvocation.getHttpRequest().getSession().getServletContext(); return (Map<String, String>)servletContext.getAttribute("urlAuthorities"); } }
4.配置文件修改
接下来,我们来修改一下SpringSecurity的配置文件,把我们自定义的这个过滤器插入到过滤器链中去。
public class SecurityUserHolder { /** * Returns the current user * * @return */ public static User getCurrentUser() { return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); } }
2.访问当前登录用户所拥有的权限
通过上面的分析,我们知道,用户所拥有的所有权限,其实是通过UserDetails接口中的getAuthorities()方法获得的。只要实现这个接口,就能实现需求。在我的代码中,不仅实现了这个接口,还在上面做了点小文章,这样我们可以获得一个用户所拥有权限的字符串表示:
/* (non-Javadoc) * @see org.springframework.security.userdetails.UserDetails#getAuthorities() */ public GrantedAuthority[] getAuthorities() { List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(roles.size()); for(Role role : roles) { grantedAuthorities.add(new GrantedAuthorityImpl(role.getName())); } return grantedAuthorities.toArray(new GrantedAuthority[roles.size()]); } /** * Returns the authorites string * * eg. * downpour --- ROLE_ADMIN,ROLE_USER * robbin --- ROLE_ADMIN * * @return */ public String getAuthoritiesString() { List<String> authorities = new ArrayList<String>(); for(GrantedAuthority authority : this.getAuthorities()) { authorities.add(authority.getAuthority()); } return StringUtils.join(authorities, ","); }
3.访问当前登录用户能够访问的资源
这就涉及到用户(User),权限(Role)和资源(Resource)三者之间的对应关系。我同样在User对象中实现了一个方法:
/** * @return the roleResources */ public Map<String, List<Resource>> getRoleResources() { // init roleResources for the first time if(this.roleResources == null) { this.roleResources = new HashMap<String, List<Resource>>(); for(Role role : this.roles) { String roleName = role.getName(); Set<Resource> resources = role.getResources(); for(Resource resource : resources) { String key = roleName + "_" + resource.getType(); if(!this.roleResources.containsKey(key)) { this.roleResources.put(key, new ArrayList<Resource>()); } this.roleResources.get(key).add(resource); } } } return this.roleResources; }
这里,会在User对象中设置一个缓存机制,在第一次取的时候,通过遍历User所有的Role,获取相应的Resource信息。
代码示例
在附件中,我给出了一个简单的例子,把我上面所讲到的所有内容整合在一起,是一个eclipse的工程,大家可以下载进行参考。