这几天学习了一下Spring Security3.1,从官网下载了Spring Security3.1版本进行练习,经过多次尝试才摸清了其中的一些原理。本人不才,希望能帮助大家。还有,这次我第二次写博客啊,文体不是很行。希望能让观看者不产生疲惫的感觉,我已经心满意足了。
一、数据库结构
先来看一下数据库结构,采用的是基于角色-资源-用户的权限管理设计。(MySql数据库)
为了节省篇章,只对比较重要的字段进行注释。
1.用户表Users
CREATE TABLE `users` (
-- 账号是否有限 1. 是 0.否
`enable` int(11) default NULL,
`password` varchar(255) default NULL,
`account` varchar(255) default NULL,
`id` int(11) NOT NULL auto_increment,
PRIMARY KEY (`id`)
)
2.角色表Roles
CREATE TABLE `roles` (
`enable` int(11) default NULL,
`name` varchar(255) default NULL,
`id` int(11) NOT NULL auto_increment,
PRIMARY KEY (`id`)
)
3 用户_角色表users_roles
CREATE TABLE `users_roles` (
--用户表的外键
`uid` int(11) default NULL,
--角色表的外键
`rid` int(11) default NULL,
`urId` int(11) NOT NULL auto_increment,
PRIMARY KEY (`urId`),
KEY `rid` (`rid`),
KEY `uid` (`uid`),
CONSTRAINT `users_roles_ibfk_1` FOREIGN KEY (`rid`)
REFERENCES `roles` (`id`),
CONSTRAINT `users_roles_ibfk_2` FOREIGN KEY (`uid`)
REFERENCES `users` (`id`)
)
4.资源表resources
CREATE TABLE `resources` (
`memo` varchar(255) default NULL,
-- 权限所对应的url地址
`url` varchar(255) default NULL,
--优先权
`priority` int(11) default NULL,
--类型
`type` int(11) default NULL,
--权限所对应的编码,例201代表发表文章
`name` varchar(255) default NULL,
`id` int(11) NOT NULL auto_increment,
PRIMARY KEY (`id`)
)
5.角色_资源表roles_resources
CREATE TABLE `roles_resources` (
`rsid` int(11) default NULL,
`rid` int(11) default NULL,
`rrId` int(11) NOT NULL auto_increment,
PRIMARY KEY (`rrId`),
KEY `rid` (`rid`),
KEY `roles_resources_ibfk_2` (`rsid`),
CONSTRAINT `roles_resources_ibfk_2` FOREIGN KEY
(`rsid`) REFERENCES `resources` (`id`),
CONSTRAINT `roles_resources_ibfk_1` FOREIGN KEY
(`rid`) REFERENCES `roles` (`id`)
)
二、系统配置
所需要的jar包,请自行到官网下载,我用的是Spring Security3.1.0.RC1版的。把dist下的除了源码件包导入就行了。还有那些零零碎的 数据库驱动啊,log4j.jar等等,我相信在用Spring Security之前,大家已经会的了。
1) web.xml
[xhtml] view plaincopyprint?
- <!-- Spring -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:applicationContext.xml,classpath:applicationContext-security.xml</param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- 10. </listener>
- 11. <!-- 权限 -->
- 12. <filter>
- 13. <filter-name>springSecurityFilterChain</filter-name>
- 14. <filter-class>
- 15. org.springframework.web.filter.DelegatingFilterProxy
- 16. </filter-class>
- 17. </filter>
- 18. <filter-mapping>
- 19. <filter-name>springSecurityFilterChain</filter-name>
- 20. <url-pattern>/*</url-pattern>
- 21. </filter-mapping>
这里主要是配置了让容器启动的时候加载application-security.xml和Spring Security的权限过滤器代理,让其过滤所有的客服请求。
2)application-security.xml
[xhtml] view plaincopyprint?
- <?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.1.xsd">
- <global-method-security pre-post-annotations="enabled" />
- <!-- 该路径下的资源不用过滤 -->
- 10. <http pattern="/js/**" security="none"/>
- 11. <http use-expressions="true" auto-config="true">
- 12.
- 13. <form-login />
- 14. <logout/>
- 15. <!-- 实现免登陆验证 -->
- 16. <remember-me />
- 17. <session-management invalid-session-url="/timeout.jsp">
- 18. <concurrency-control max-sessions="10" error-if-maximum-exceeded="true" />
- 19. </session-management>
- 20. <custom-filter ref="myFilter" before="FILTER_SECURITY_INTERCEPTOR"/>
- 21. </http>
- 22. <!-- 配置过滤器 -->
- 23. <beans:bean id="myFilter" class="com.huaxin.security.MySecurityFilter">
- 24. <!-- 用户拥有的权限 -->
- 25. <beans:property name="authenticationManager" ref="myAuthenticationManager" />
- 26. <!-- 用户是否拥有所请求资源的权限 -->
- 27. <beans:property name="accessDecisionManager" ref="myAccessDecisionManager" />
- 28. <!-- 资源与权限对应关系 -->
- 29. <beans:property name="securityMetadataSource" ref="mySecurityMetadataSource" />
- 30. </beans:bean>
- 31. <!-- 实现了UserDetailsService的Bean -->
- 32. <authentication-manager alias="myAuthenticationManager">
- 33. <authentication-provider user-service-ref="myUserDetailServiceImpl" />
- 34. </authentication-manager>
- 35. <beans:bean id="myAccessDecisionManager" class="com.huaxin.security.MyAccessDecisionManager"></beans:bean>
- 36. <beans:bean id="mySecurityMetadataSource" class="com.huaxin.security.MySecurityMetadataSource">
- 37. <beans:constructor-arg name="resourcesDao" ref="resourcesDao"></beans:constructor-arg>
- 38. </beans:bean>
- 39. <beans:bean id="myUserDetailServiceImpl" class="com.huaxin.security.MyUserDetailServiceImpl">
- 40. <beans:property name="usersDao" ref="usersDao"></beans:property>
- 41. </beans:bean>
42. </beans:beans>
我们在第二个http标签下配置一个我们自定义的继承了org.springframework.security.access.intercept.AbstractSecurityInterceptor的Filter,并注入其
必须的3个组件authenticationManager、accessDecisionManager和securityMetadataSource。其作用上面已经注释了。
<custom-filter ref="myFilter" before="FILTER_SECURITY_INTERCEPTOR"/> 这里的FILTER_SECURITY_INTERCEPTOR是Spring Security默认的Filter,
我们自定义的Filter必须在它之前,过滤客服请求。接下来看下我们最主要的myFilter吧。
3)myFilter
(1) MySecurityFilter.java 过滤用户请求
[java] view plaincopyprint?
- public class MySecurityFilter extends AbstractSecurityInterceptor implements Filter {
- //与applicationContext-security.xml里的myFilter的属性securityMetadataSource对应,
- //其他的两个组件,已经在AbstractSecurityInterceptor定义
- private FilterInvocationSecurityMetadataSource securityMetadataSource;
- @Override
- public SecurityMetadataSource obtainSecurityMetadataSource() {
- return this.securityMetadataSource;
- }
- 10.
- 11. public void doFilter(ServletRequest request, ServletResponse response,
- 12. FilterChain chain) throws IOException, ServletException {
- 13. FilterInvocation fi = new FilterInvocation(request, response, chain);
- 14. invoke(fi);
- 15. }
- 16.
- 17. private void invoke(FilterInvocation fi) throws IOException, ServletException {
- 18. // object为FilterInvocation对象
- 19. //super.beforeInvocation(fi);源码
- 20. //1.获取请求资源的权限
- 21. //执行Collection<ConfigAttribute> attributes = SecurityMetadataSource.getAttributes(object);
- 22. //2.是否拥有权限
- 23. //this.accessDecisionManager.decide(authenticated, object, attributes);
- 24. InterceptorStatusToken token = super.beforeInvocation(fi);
- 25. try {
- 26. fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
- 27. } finally {
- 28. super.afterInvocation(token, null);
- 29. }
- 30. }
- 31.
- 32. public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
- 33. return securityMetadataSource;
- 34. }
- 35.
- 36. public void setSecurityMetadataSource(FilterInvocationSecurityMetadataSource securityMetadataSource) {
- 37. this.securityMetadataSource = securityMetadataSource;
- 38. }
- 39.
- 40. public void init(FilterConfig arg0) throws ServletException {
- 41. // TODO Auto-generated method stub
- 42. }
- 43.
- 44. public void destroy() {
- 45. // TODO Auto-generated method stub
- 46.
- 47. }
- 48.
- 49. @Override
- 50. public Class<? extends Object> getSecureObjectClass() {
- 51. //下面的MyAccessDecisionManager的supports方面必须放回true,否则会提醒类型错误
- 52. return FilterInvocation.class;
- 53. }
54. }
核心的InterceptorStatusToken token = super.beforeInvocation(fi);会调用我们定义的accessDecisionManager:decide(Object object)和securityMetadataSource
:getAttributes(Object object)方法。
(2)MySecurityMetadataSource.java
[java] view plaincopyprint?
- //1 加载资源与权限的对应关系
- public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
- //由spring调用
- public MySecurityMetadataSource(ResourcesDao resourcesDao) {
- this.resourcesDao = resourcesDao;
- loadResourceDefine();
- }
- private ResourcesDao resourcesDao;
- 10. private static Map<String, Collection<ConfigAttribute>> resourceMap = null;
- 11.
- 12. public ResourcesDao getResourcesDao() {
- 13. return resourcesDao;
- 14. }
- 15.
- 16. public void setResourcesDao(ResourcesDao resourcesDao) {
- 17. this.resourcesDao = resourcesDao;
- 18. }
- 19.
- 20. public Collection<ConfigAttribute> getAllConfigAttributes() {
- 21. // TODO Auto-generated method stub
- 22. return null;
- 23. }
- 24.
- 25. public boolean supports(Class<?> clazz) {
- 26. // TODO Auto-generated method stub
- 27. return true;
- 28. }
- 29. //加载所有资源与权限的关系
- 30. private void loadResourceDefine() {
- 31. if(resourceMap == null) {
- 32. resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
- 33. List<Resources> resources = this.resourcesDao.findAll();
- 34. for (Resources resource : resources) {
- 35. Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
- 36. //以权限名封装为Spring的security Object
- 37. ConfigAttribute configAttribute = new SecurityConfig(resource.getName());
- 38. configAttributes.add(configAttribute);
- 39. resourceMap.put(resource.getUrl(), configAttributes);
- 40. }
- 41. }
- 42.
- 43. Set<Entry<String, Collection<ConfigAttribute>>> resourceSet = resourceMap.entrySet();
- 44. Iterator<Entry<String, Collection<ConfigAttribute>>> iterator = resourceSet.iterator();
- 45.
- 46. }
- 47. //返回所请求资源所需要的权限
- 48. public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
- 49.
- 50. String requestUrl = ((FilterInvocation) object).getRequestUrl();
- 51. System.out.println("requestUrl is " + requestUrl);
- 52. if(resourceMap == null) {
- 53. loadResourceDefine();
- 54. }
- 55. return resourceMap.get(requestUrl);
- 56. }
- 57.
58. }
这里的resourcesDao,熟悉Dao设计模式和Spring 注入的朋友应该看得明白。
(3)MyUserDetailServiceImpl.java
[java] view plaincopyprint?
- public class MyUserDetailServiceImpl implements UserDetailsService {
- private UsersDao usersDao;
- public UsersDao getUsersDao() {
- return usersDao;
- }
- public void setUsersDao(UsersDao usersDao) {
- this.usersDao = usersDao;
- 10. }
- 11.
- 12. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
- 13. System.out.println("username is " + username);
- 14. Users users = this.usersDao.findByName(username);
- 15. if(users == null) {
- 16. throw new UsernameNotFoundException(username);
- 17. }
- 18. Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(users);
- 19.
- 20. boolean enables = true;
- 21. boolean accountNonExpired = true;
- 22. boolean credentialsNonExpired = true;
- 23. boolean accountNonLocked = true;
- 24.
- 25. User userdetail = new User(users.getAccount(), users.getPassword(), enables, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);
- 26. return userdetail;
- 27. }
- 28.
- 29. //取得用户的权限
- 30. private Set<GrantedAuthority> obtionGrantedAuthorities(Users user) {
- 31. Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
- 32. Set<Roles> roles = user.getRoles();
- 33.
- 34. for(Roles role : roles) {
- 35. Set<Resources> tempRes = role.getResources();
- 36. for(Resources res : tempRes) {
- 37. authSet.add(new GrantedAuthorityImpl(res.getName()));
38. s }
- 39. }
- 40. return authSet;
- 41. }
42. }
(4) MyAccessDecisionManager.java
[java] view plaincopyprint?
- public class MyAccessDecisionManager implements AccessDecisionManager {
- public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
- if(configAttributes == null) {
- return;
- }
- //所请求的资源拥有的权限(一个资源对多个权限)
- Iterator<ConfigAttribute> iterator = configAttributes.iterator();
- while(iterator.hasNext()) {
- 10. ConfigAttribute configAttribute = iterator.next();
- 11. //访问所请求资源所需要的权限
- 12. String needPermission = configAttribute.getAttribute();
- 13. System.out.println("needPermission is " + needPermission);
- 14. //用户所拥有的权限authentication
- 15. for(GrantedAuthority ga : authentication.getAuthorities()) {
- 16. if(needPermission.equals(ga.getAuthority())) {
- 17. return;
- 18. }
- 19. }
- 20. }
- 21. //没有权限
- 22. throw new AccessDeniedException(" 没有权限访问! ");
- 23. }
- 24.
- 25. public boolean supports(ConfigAttribute attribute) {
- 26. // TODO Auto-generated method stub
- 27. return true;
- 28. }
- 29.
- 30. public boolean supports(Class<?> clazz) {
- 31. // TODO Auto-generated method stub
- 32. return true;
- 33. }
- 34.
35. }
三、流程
1)容器启动(MySecurityMetadataSource:loadResourceDefine加载系统资源与权限列表)
2)用户发出请求
3)过滤器拦截(MySecurityFilter:doFilter)
4)取得请求资源所需权限(MySecurityMetadataSource:getAttributes)
5)匹配用户拥有权限和请求权限(MyAccessDecisionManager:decide),如果用户没有相应的权限,
执行第6步,否则执行第7步。
6)登录
7)验证并授权(MyUserDetailServiceImpl:loadUserByUsername)
8)重复4,5
分享到: