ITeye博客

spring security3进级篇III

snoopy7713 · 2012-11-28 13:08 · spring--security · 行业应用 · Spring · Security · Markdown

在spring security3进级篇II中,虽然将用户和权限存入到数据库中,但在配置文件中仍然要对URL地址配置角色进行控制访问,如何将用户,角色,资源存放 到数据库中,进行统一管理,逐步实现RBAC的模型呢,这需要更复杂的实现,这一篇将实现将所有的信息存储到数据库中,但不涉及组,许可等表。

 

1、首先建立数据表

Sql代码  收藏代码

  1. CREATE   DATABASE  IF  NOT  EXISTS spring_securityiii;
  2. USE spring_securityiii;
  3. --
  4. -- Definition of table `pub_resources`
  5. --
  6. DROP   TABLE  IF EXISTS `pub_resources`;
  7. CREATE   TABLE  `pub_resources` (
  8. `id` bigint (20)  NOT   NULL  AUTO_INCREMENT,
  9. `resource_name` varchar (50)  NOT   NULL ,
  10. `resource_type` varchar (50)  NOT   NULL ,
  11. `resource_string` varchar (200)  NOT   NULL ,
  12. `resource_enabled` tinyint(1) NOT   NULL ,
  13. `resource_desc` varchar (200)  DEFAULT   NULL ,
  14. PRIMARY   KEY  (`id`),
  15. UNIQUE   KEY  `uk_pub_resource` (`resource_name`)
  16. ) ENGINE=InnoDB AUTO_INCREMENT=402 DEFAULT  CHARSET=utf8;
  17. --
  18. -- Dumping data for table `pub_resources`
  19. --
  20. /*!40000 ALTER   TABLE  `pub_resources` DISABLE KEYS */;
  21. INSERT   INTO  `pub_resources` (`id`,`resource_name`,`resource_type`,`resource_string`,`resource_enabled`,`resource_desc`)  VALUES
  22. (400,'index页面' , 'url' , '/index.*' ,1, 'index页面' ),
  23. (401,'admin页面' , 'url' , '/admin.*' ,1, 'admin页面' );
  24. /*!40000 ALTER   TABLE  `pub_resources` ENABLE KEYS */;
  25. --
  26. -- Definition of table `pub_roles`
  27. --
  28. DROP   TABLE  IF EXISTS `pub_roles`;
  29. CREATE   TABLE  `pub_roles` (
  30. `id` bigint (20)  NOT   NULL  AUTO_INCREMENT,
  31. `role_name` varchar (100)  NOT   NULL ,
  32. `role_enabled` tinyint(1) NOT   NULL ,
  33. `role_desc` varchar (200)  DEFAULT   NULL ,
  34. PRIMARY   KEY  (`id`),
  35. UNIQUE   KEY  `uk_pub_role` (`role_name`)
  36. ) ENGINE=InnoDB AUTO_INCREMENT=202 DEFAULT  CHARSET=utf8;
  37. --
  38. -- Dumping data for table `pub_roles`
  39. --
  40. /*!40000 ALTER   TABLE  `pub_roles` DISABLE KEYS */;
  41. INSERT   INTO  `pub_roles` (`id`,`role_name`,`role_enabled`,`role_desc`)  VALUES
  42. (200,'ROLE_ADMIN' ,1, '管理员角色' ),
  43. (201,'ROLE_USER' ,1, '普通用户角色' );
  44. /*!40000 ALTER   TABLE  `pub_roles` ENABLE KEYS */;
  45. --
  46. -- Definition of table `pub_roles_resources`
  47. --
  48. DROP   TABLE  IF EXISTS `pub_roles_resources`;
  49. CREATE   TABLE  `pub_roles_resources` (
  50. `id` bigint (20)  NOT   NULL  AUTO_INCREMENT,
  51. `role_id` bigint (20)  NOT   NULL ,
  52. `resource_id` bigint (20)  NOT   NULL ,
  53. PRIMARY   KEY  (`id`),
  54. KEY  `roles_resources_ibfk_1` (`role_id`),
  55. KEY  `roles_resources_ibfk_2` (`resource_id`),
  56. CONSTRAINT  `roles_resources_ibfk_1`  FOREIGN   KEY  (`role_id`)  REFERENCES  `pub_roles` (`id`),
  57. CONSTRAINT  `roles_resources_ibfk_2`  FOREIGN   KEY  (`resource_id`)  REFERENCES  `pub_resources` (`id`)
  58. ) ENGINE=InnoDB AUTO_INCREMENT=503 DEFAULT  CHARSET=utf8;
  59. --
  60. -- Dumping data for table `pub_roles_resources`
  61. --
  62. /*!40000 ALTER   TABLE  `pub_roles_resources` DISABLE KEYS */;
  63. INSERT   INTO  `pub_roles_resources` (`id`,`role_id`,`resource_id`)  VALUES
  64. (500,200,400),
  65. (501,200,401),
  66. (502,201,400);
  67. /*!40000 ALTER   TABLE  `pub_roles_resources` ENABLE KEYS */;
  68. --
  69. -- Definition of table `pub_users`
  70. --
  71. DROP   TABLE  IF EXISTS `pub_users`;
  72. CREATE   TABLE  `pub_users` (
  73. `id` bigint (20)  NOT   NULL  AUTO_INCREMENT,
  74. `user_account` varchar (50)  NOT   NULL ,
  75. `user_password` varchar (20)  NOT   NULL ,
  76. `user_enabled` tinyint(1) NOT   NULL ,
  77. `user_desc` varchar (200)  DEFAULT   NULL ,
  78. PRIMARY   KEY  (`id`),
  79. UNIQUE   KEY  `uk_pub_user` (`user_account`)
  80. ) ENGINE=InnoDB AUTO_INCREMENT=102 DEFAULT  CHARSET=utf8;
  81. --
  82. -- Dumping data for table `pub_users`
  83. --
  84. /*!40000 ALTER   TABLE  `pub_users` DISABLE KEYS */;
  85. INSERT   INTO  `pub_users` (`id`,`user_account`,`user_password`,`user_enabled`,`user_desc`)  VALUES
  86. (100,'admin' , 'admin' ,1, '管理员' ),
  87. (101,'user' , 'user' ,1, '普通用户' );
  88. /*!40000 ALTER   TABLE  `pub_users` ENABLE KEYS */;
  89. --
  90. -- Definition of table `pub_users_roles`
  91. --
  92. DROP   TABLE  IF EXISTS `pub_users_roles`;
  93. CREATE   TABLE  `pub_users_roles` (
  94. `id` bigint (20)  NOT   NULL  AUTO_INCREMENT,
  95. `user_id` bigint (20)  NOT   NULL ,
  96. `role_id` bigint (20)  NOT   NULL ,
  97. `ur_enabled` tinyint(1) NOT   NULL ,
  98. PRIMARY   KEY  (`id`),
  99. KEY  `users_roles_ibfk_1` (`user_id`),
  100. KEY  `users_roles_ibfk_2` (`role_id`),
  101. CONSTRAINT  `users_roles_ibfk_1`  FOREIGN   KEY  (`user_id`)  REFERENCES  `pub_users` (`id`),
  102. CONSTRAINT  `users_roles_ibfk_2`  FOREIGN   KEY  (`role_id`)  REFERENCES  `pub_roles` (`id`)
  103. ) ENGINE=InnoDB AUTO_INCREMENT=303 DEFAULT  CHARSET=utf8;
  104. --
  105. -- Dumping data for table `pub_users_roles`
  106. --
  107. /*!40000 ALTER   TABLE  `pub_users_roles` DISABLE KEYS */;
  108. INSERT   INTO  `pub_users_roles` (`id`,`user_id`,`role_id`,`ur_enabled`)  VALUES
  109. (300,100,200,1),
  110. (301,100,201,1),
  111. (302,101,201,1);
  112. /*!40000 ALTER   TABLE  `pub_users_roles` ENABLE KEYS */;

 2、自定义实现spring security的四个类

 

Java代码  收藏代码

  1. package  com.spring.security.service.impl;
  2. import  javax.annotation.Resource;
  3. import  org.springframework.security.core.userdetails.UserDetails;
  4. import  org.springframework.security.core.userdetails.UsernameNotFoundException;
  5. import  org.springframework.stereotype.Service;
  6. import  com.spring.security.dao.UserDao;
  7. import  com.spring.security.domain.User;
  8. import  com.spring.security.service.CustomUserDetailsService;
  9. @Service ( "customUserDetailsService" )
  10. public   class  CustomUserDetailsServiceImpl  implements  CustomUserDetailsService {
  11. @Resource
  12. private  UserDao userDao;
  13. @Override
  14. public  UserDetails loadUserByUsername(String userName) throws  UsernameNotFoundException {
  15. User user = userDao.findUserByName(userName);
  16. if  (user ==  null ) {
  17. throw   new  UsernameNotFoundException( "用户名"  + userName +  "不存在" );
  18. }
  19. // 因为User已经实现了UserDetails接口,所以直接返回user即可
  20. return  user;
  21. }
  22. }

 

Java代码  收藏代码

  1. package  com.spring.security.service.impl;
  2. import  java.util.Collection;
  3. import  java.util.Iterator;
  4. import  org.springframework.security.access.AccessDeniedException;
  5. import  org.springframework.security.access.ConfigAttribute;
  6. import  org.springframework.security.access.SecurityConfig;
  7. import  org.springframework.security.authentication.InsufficientAuthenticationException;
  8. import  org.springframework.security.core.Authentication;
  9. import  org.springframework.security.core.GrantedAuthority;
  10. import  org.springframework.stereotype.Service;
  11. import  com.spring.security.service.CustomAccessDecisionManager;
  12. /**
  13. * AccessdecisionManager在Spring security中是很重要的。
  14. *
  15. * 在验证部分简略提过了,所有的Authentication实现需要保存在一个GrantedAuthority对象数组中。 这就是赋予给主体的权限。
  16. * GrantedAuthority对象通过AuthenticationManager 保存到
  17. * Authentication对象里,然后从AccessDecisionManager读出来,进行授权判断。
  18. *
  19. * Spring Security提供了一些拦截器,来控制对安全对象的访问权限,例如方法调用或web请求。
  20. * 一个是否允许执行调用的预调用决定,是由AccessDecisionManager实现的。 这个 AccessDecisionManager
  21. * 被AbstractSecurityInterceptor调用, 它用来作最终访问控制的决定。
  22. * 这个AccessDecisionManager接口包含三个方法:
  23. *
  24. * void decide(Authentication authentication, Object secureObject,
  25. * List<ConfigAttributeDefinition> config) throws AccessDeniedException; boolean
  26. * supports(ConfigAttribute attribute); boolean supports(Class clazz);
  27. *
  28. * 从第一个方法可以看出来,AccessDecisionManager使用方法参数传递所有信息,这好像在认证评估时进行决定。
  29. * 特别是,在真实的安全方法期望调用的时候,传递安全Object启用那些参数。 比如,让我们假设安全对象是一个MethodInvocation。
  30. * 很容易为任何Customer参数查询MethodInvocation,
  31. * 然后在AccessDecisionManager里实现一些有序的安全逻辑,来确认主体是否允许在那个客户上操作。
  32. * 如果访问被拒绝,实现将抛出一个AccessDeniedException异常。
  33. *
  34. * 这个 supports(ConfigAttribute) 方法在启动的时候被
  35. * AbstractSecurityInterceptor调用,来决定AccessDecisionManager
  36. * 是否可以执行传递ConfigAttribute。 supports(Class)方法被安全拦截器实现调用,
  37. * 包含安全拦截器将显示的AccessDecisionManager支持安全对象的类型。
  38. */
  39. @Service ( "customAccessDecisionManager" )
  40. public   class  CustomAccessDecisionManagerImpl  implements  CustomAccessDecisionManager {
  41. /* (non-Javadoc)
  42. * @see org.springframework.security.access.AccessDecisionManager#decide(org.springframework.security.core.Authentication, java.lang.Object, java.util.Collection)
  43. */
  44. public   void  decide(Authentication authentication, Object object,Collection<ConfigAttribute> configAttributes)
  45. throws  AccessDeniedException, InsufficientAuthenticationException {
  46. if  (configAttributes ==  null ) {
  47. return ;
  48. }
  49. Iterator<ConfigAttribute> ite = configAttributes.iterator();
  50. while  (ite.hasNext()) {
  51. ConfigAttribute ca = ite.next();
  52. String needRole = ((SecurityConfig) ca).getAttribute();
  53. // ga 为用户所被赋予的权限。 needRole 为访问相应的资源应该具有的权限。
  54. for  (GrantedAuthority ga : authentication.getAuthorities()) {
  55. if  (needRole.trim().equals(ga.getAuthority().trim())) {
  56. return ;
  57. }
  58. }
  59. }
  60. throw   new  AccessDeniedException( "Acess Denied" );
  61. }
  62. /* (non-Javadoc)
  63. * @see org.springframework.security.access.AccessDecisionManager#supports(org.springframework.security.access.ConfigAttribute)
  64. */
  65. public   boolean  supports(ConfigAttribute attribute) {
  66. return   true ;
  67. }
  68. /* (non-Javadoc)
  69. * @see org.springframework.security.access.AccessDecisionManager#supports(java.lang.Class)
  70. */
  71. public   boolean  supports(Class<?> clazz) {
  72. return   true ;
  73. }
  74. }

 

Java代码  收藏代码

  1. package  com.spring.security.service.impl;
  2. import  java.io.IOException;
  3. import  javax.servlet.FilterChain;
  4. import  javax.servlet.FilterConfig;
  5. import  javax.servlet.ServletException;
  6. import  javax.servlet.ServletRequest;
  7. import  javax.servlet.ServletResponse;
  8. import  org.springframework.security.access.SecurityMetadataSource;
  9. import  org.springframework.security.access.intercept.AbstractSecurityInterceptor;
  10. import  org.springframework.security.access.intercept.InterceptorStatusToken;
  11. import  org.springframework.security.web.FilterInvocation;
  12. import  org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
  13. import  org.springframework.stereotype.Service;
  14. import  com.spring.security.service.CustomFilterSecurityInterceptor;
  15. /** */
  16. /**
  17. * 该过滤器的主要作用就是通过spring著名的IoC生成securityMetadataSource。
  18. * securityMetadataSource相当于本包中自定义的MyInvocationSecurityMetadataSourceService。
  19. * 该MyInvocationSecurityMetadataSourceService的作用提从数据库提取权限和资源,装配到HashMap中,
  20. * 供Spring Security使用,用于权限校验。
  21. *
  22. */
  23. @Service ( "customFilterSecurityInterceptor" )
  24. public   class  CustomFilterSecurityInterceptorImpl  extends  AbstractSecurityInterceptor  implements  CustomFilterSecurityInterceptor {
  25. private  FilterInvocationSecurityMetadataSource securityMetadataSource;
  26. public   void  setSecurityMetadataSource(
  27. FilterInvocationSecurityMetadataSource securityMetadataSource) {
  28. this .securityMetadataSource = securityMetadataSource;
  29. }
  30. public   void  doFilter(ServletRequest request, ServletResponse response,FilterChain chain)  throws  IOException, ServletException {
  31. FilterInvocation fi = new  FilterInvocation(request, response, chain);
  32. invoke(fi);
  33. }
  34. public  FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
  35. return   this .securityMetadataSource;
  36. }
  37. public  Class<?  extends  Object> getSecureObjectClass() {
  38. return  FilterInvocation. class ;
  39. }
  40. public   void  invoke(FilterInvocation fi)  throws  IOException,ServletException {
  41. InterceptorStatusToken token = super .beforeInvocation(fi);
  42. try  {
  43. fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
  44. } finally  {
  45. super .afterInvocation(token,  null );
  46. }
  47. }
  48. @Override
  49. public  SecurityMetadataSource obtainSecurityMetadataSource() {
  50. return   this .securityMetadataSource;
  51. }
  52. public   void  destroy() {
  53. }
  54. public   void  init(FilterConfig filterconfig)  throws  ServletException {
  55. }
  56. }

 

Java代码  收藏代码

  1. package  com.spring.security.service.impl;
  2. import  java.util.ArrayList;
  3. import  java.util.Collection;
  4. import  java.util.HashMap;
  5. import  java.util.HashSet;
  6. import  java.util.Iterator;
  7. import  java.util.List;
  8. import  java.util.Map;
  9. import  java.util.Set;
  10. import  javax.annotation.PostConstruct;
  11. import  javax.servlet.http.HttpServletRequest;
  12. import  org.springframework.security.access.ConfigAttribute;
  13. import  org.springframework.security.access.SecurityConfig;
  14. import  org.springframework.security.web.FilterInvocation;
  15. import  org.springframework.security.web.util.AntPathRequestMatcher;
  16. import  org.springframework.stereotype.Service;
  17. import  com.spring.security.dao.ResourceDao;
  18. import  com.spring.security.domain.Resource;
  19. import  com.spring.security.domain.Role;
  20. import  com.spring.security.service.CustomInvocationSecurityMetadataSource;
  21. @Service ( "customInvocationSecurityMetadataSource" )
  22. public   class  CustomInvocationSecurityMetadataSourceImpl  implements  CustomInvocationSecurityMetadataSource {
  23. @javax .annotation.Resource
  24. private  ResourceDao resourceDao;
  25. private  AntPathRequestMatcher pathMatcher;
  26. private  HashMap<String, Collection<ConfigAttribute>> resourceMap =  null ;
  27. /**
  28. * 自定义方法,这个类放入到Spring容器后,
  29. * 指定init为初始化方法,从数据库中读取资源
  30. *
  31. */
  32. @PostConstruct
  33. public   void  init(){
  34. this .resourceMap =  new  HashMap<String, Collection<ConfigAttribute>>();
  35. for  (Resource item : resourceDao.getAllResource()) {
  36. resourceMap.put(item.getResource_string(), listToCollection(item.getRoles()));
  37. }
  38. }
  39. @Override
  40. public  Collection<ConfigAttribute> getAllConfigAttributes() {
  41. Set<ConfigAttribute> allAttributes = new  HashSet<ConfigAttribute>();
  42. for  (Map.Entry<String, Collection<ConfigAttribute>> entry : resourceMap.entrySet()) {
  43. allAttributes.addAll(entry.getValue());
  44. }
  45. return  allAttributes;
  46. }
  47. @Override
  48. public  Collection<ConfigAttribute> getAttributes(Object object) throws  IllegalArgumentException {
  49. HttpServletRequest request = ((FilterInvocation) object).getRequest();
  50. System.out.println("requestUrl is "  + request.getRequestURI());
  51. if  (resourceMap ==  null ) {
  52. this .loadAllResourcesAndAuthorities();
  53. }
  54. Iterator<String> it = resourceMap.keySet().iterator();
  55. while  (it.hasNext()) {
  56. String resURL = it.next();
  57. pathMatcher = new  AntPathRequestMatcher(resURL);
  58. if  (pathMatcher.matches(request)) {
  59. Collection<ConfigAttribute> returnCollection = resourceMap.get(resURL);
  60. return  returnCollection;
  61. }
  62. }
  63. return   null ;
  64. }
  65. @Override
  66. public   boolean  supports(Class<?> arg0) {
  67. // TODO Auto-generated method stub
  68. return   true ;
  69. }
  70. /**
  71. * 自定义方法,将List<Role>集合转换为框架需要的Collection<ConfigAttribute>集合
  72. *
  73. * @param roles
  74. * @return
  75. */
  76. private  Collection<ConfigAttribute> listToCollection(List<Role> roles) {
  77. List<ConfigAttribute> list = new  ArrayList<ConfigAttribute>();
  78. for  (Role role : roles) {
  79. list.add(new  SecurityConfig(role.getRole_name()));
  80. }
  81. return  list;
  82. }
  83. /**
  84. * 加载所有资源与权限的关系
  85. */
  86. private   void  loadAllResourcesAndAuthorities() {
  87. if  (resourceMap ==  null ) {
  88. resourceMap = new  HashMap<String, Collection<ConfigAttribute>>();
  89. }
  90. List<Resource> resources = this .resourceDao.getAllResource();
  91. for  (Resource resource : resources) {
  92. resourceMap.put(resource.getResource_string(),listToCollection(resource.getRoles()));
  93. }
  94. }
  95. }

 

3、定义用户,角色,资源的类

 

Java代码  收藏代码

  1. package  com.spring.security.domain;
  2. import  java.io.Serializable;
  3. import  java.util.ArrayList;
  4. import  java.util.List;
  5. /**
  6. * Resources
  7. */
  8. public   class  Resource  implements  Serializable {
  9. private   static   final   long  serialVersionUID = 1L;
  10. private  Integer id;
  11. private  String resource_name;
  12. private  String resource_type;
  13. private  String resource_string;
  14. private  String resource_enabled;
  15. private  String resource_desc;
  16. private  List<Role> roles =  new  ArrayList<Role>();
  17. public  Integer getId() {
  18. return  id;
  19. }
  20. public   void  setId(Integer id) {
  21. this .id = id;
  22. }
  23. public  String getResource_name() {
  24. return  resource_name;
  25. }
  26. public   void  setResource_name(String resource_name) {
  27. this .resource_name = resource_name;
  28. }
  29. public  String getResource_type() {
  30. return  resource_type;
  31. }
  32. public   void  setResource_type(String resource_type) {
  33. this .resource_type = resource_type;
  34. }
  35. public  String getResource_string() {
  36. return  resource_string;
  37. }
  38. public   void  setResource_string(String resource_string) {
  39. this .resource_string = resource_string;
  40. }
  41. public  String getResource_enabled() {
  42. return  resource_enabled;
  43. }
  44. public   void  setResource_enabled(String resource_enabled) {
  45. this .resource_enabled = resource_enabled;
  46. }
  47. public  String getResource_desc() {
  48. return  resource_desc;
  49. }
  50. public   void  setResource_desc(String resource_desc) {
  51. this .resource_desc = resource_desc;
  52. }
  53. public  List<Role> getRoles() {
  54. return  roles;
  55. }
  56. public   void  setRoles(List<Role> roles) {
  57. this .roles = roles;
  58. }
  59. }

 

Java代码  收藏代码

  1. package  com.spring.security.domain;
  2. import  java.io.Serializable;
  3. /**
  4. * Roles.
  5. */
  6. public   class  Role  implements  Serializable {
  7. private   static   final   long  serialVersionUID = 1L;
  8. private  Integer id;
  9. private  String role_name;
  10. private  Integer role_enabled;
  11. private  String role_desc;
  12. public  Role() {
  13. }
  14. public  Integer getId() {
  15. return  id;
  16. }
  17. public   void  setId(Integer id) {
  18. this .id = id;
  19. }
  20. public  String getRole_name() {
  21. return  role_name;
  22. }
  23. public   void  setRole_name(String role_name) {
  24. this .role_name = role_name;
  25. }
  26. public  Integer getRole_enabled() {
  27. return  role_enabled;
  28. }
  29. public   void  setRole_enabled(Integer role_enabled) {
  30. this .role_enabled = role_enabled;
  31. }
  32. public  String getRole_desc() {
  33. return  role_desc;
  34. }
  35. public   void  setRole_desc(String role_desc) {
  36. this .role_desc = role_desc;
  37. }
  38. }

 

Java代码  收藏代码

  1. package  com.spring.security.domain;
  2. import  java.io.Serializable;
  3. import  java.util.ArrayList;
  4. import  java.util.Collection;
  5. import  java.util.List;
  6. import  org.springframework.security.core.GrantedAuthority;
  7. import  org.springframework.security.core.authority.SimpleGrantedAuthority;
  8. import  org.springframework.security.core.userdetails.UserDetails;
  9. public   class  User  implements  UserDetails, Serializable {
  10. private   static   final   long  serialVersionUID = 1L;
  11. private  Integer id;
  12. private  String user_account;
  13. private  Integer user_enabled;
  14. private  String user_password;
  15. private  String user_desc;
  16. private  List<Role> roles =  new  ArrayList<Role>();
  17. public  User() {
  18. }
  19. public  Integer getId() {
  20. return  id;
  21. }
  22. public   void  setId(Integer id) {
  23. this .id = id;
  24. }
  25. public  String getUser_account() {
  26. return  user_account;
  27. }
  28. public   void  setUser_account(String user_account) {
  29. this .user_account = user_account;
  30. }
  31. public  Integer getUser_enabled() {
  32. return  user_enabled;
  33. }
  34. public   void  setUser_enabled(Integer user_enabled) {
  35. this .user_enabled = user_enabled;
  36. }
  37. public  String getUser_password() {
  38. return  user_password;
  39. }
  40. public   void  setUser_password(String user_password) {
  41. this .user_password = user_password;
  42. }
  43. public  String getUser_desc() {
  44. return  user_desc;
  45. }
  46. public   void  setUser_desc(String user_desc) {
  47. this .user_desc = user_desc;
  48. }
  49. public  List<Role> getRoles() {
  50. return  roles;
  51. }
  52. public   void  setRoles(List<Role> roles) {
  53. this .roles = roles;
  54. }
  55. /*
  56. * 获取用户权限集合,权限使用GrantedAuthority接口表示,框架中有它的实现类
  57. * GrantedAuthorityImpl,只需要把角色的名称放入即可 (non-Javadoc)
  58. *
  59. * @see
  60. * org.springframework.security.core.userdetails.UserDetails#getAuthorities
  61. * ()
  62. */
  63. @Override
  64. public  Collection<?  extends  GrantedAuthority> getAuthorities() {
  65. List<GrantedAuthority> list = new  ArrayList<GrantedAuthority>();
  66. for  (Role role : roles) {
  67. list.add(new  SimpleGrantedAuthority(role.getRole_name()));
  68. }
  69. return  list;
  70. }
  71. /*
  72. * 获取用户名 (non-Javadoc)
  73. *
  74. * @see
  75. * org.springframework.security.core.userdetails.UserDetails#getUsername()
  76. */
  77. @Override
  78. public  String getUsername() {
  79. // TODO Auto-generated method stub
  80. return   this .user_account;
  81. }
  82. /*
  83. * 用户密码 (non-Javadoc)
  84. *
  85. * @see
  86. * org.springframework.security.core.userdetails.UserDetails#getPassword()
  87. */
  88. @Override
  89. public  String getPassword() {
  90. // TODO Auto-generated method stub
  91. return   this .user_password;
  92. }
  93. /*
  94. * 直接返回true,表示没有过期 (non-Javadoc)
  95. *
  96. * @see
  97. * org.springframework.security.core.userdetails.UserDetails#isAccountNonExpired
  98. * ()
  99. */
  100. @Override
  101. public   boolean  isAccountNonExpired() {
  102. // TODO Auto-generated method stub
  103. return   true ;
  104. }
  105. /*
  106. * 直接返回true,表示没有锁定 (non-Javadoc)
  107. *
  108. * @see
  109. * org.springframework.security.core.userdetails.UserDetails#isAccountNonLocked
  110. * ()
  111. */
  112. @Override
  113. public   boolean  isAccountNonLocked() {
  114. // TODO Auto-generated method stub
  115. return   true ;
  116. }
  117. @Override
  118. public   boolean  isCredentialsNonExpired() {
  119. // TODO Auto-generated method stub
  120. return   true ;
  121. }
  122. /*
  123. * 是否禁用 (non-Javadoc)
  124. *
  125. * @see
  126. * org.springframework.security.core.userdetails.UserDetails#isEnabled()
  127. */
  128. @Override
  129. public   boolean  isEnabled() {
  130. // TODO Auto-generated method stub
  131. return   true ;
  132. }
  133. }

 4 用户,资源,角色DAo类的实现

Java代码  收藏代码

  1. package  com.spring.security.dao.impl;
  2. import  java.sql.ResultSet;
  3. import  java.sql.SQLException;
  4. import  java.util.List;
  5. import  org.springframework.jdbc.core.BeanPropertyRowMapper;
  6. import  org.springframework.jdbc.core.RowMapper;
  7. import  org.springframework.stereotype.Repository;
  8. import  com.spring.security.dao.UserDao;
  9. import  com.spring.security.dao.support.SimpleDaoSupport;
  10. import  com.spring.security.domain.Role;
  11. import  com.spring.security.domain.User;
  12. @Repository ( "userDao" )
  13. public   class  UserDaoImpl  extends  SimpleDaoSupport  implements  UserDao {
  14. @Override
  15. public  User findUserByName(String userName) {
  16. String sql = "SELECT id,user_account,user_enabled,user_password,user_desc FROM pub_users where user_account=?" ;
  17. return   this .getSimpleJdbcTemplate().queryForObject(sql,
  18. new  UserMapper(), userName);
  19. }
  20. /**
  21. * 获取User对象的role列表
  22. *
  23. * @param userID
  24. * @return RoleList
  25. */
  26. public  List<Role> getRolesByUserID(String userName) {
  27. String sql = "SELECT r.id,r.role_name,r.role_enabled,r.role_desc FROM pub_users u,pub_roles r,pub_users_roles ur "
  28. + "WHERE u.id=ur.user_id AND r.id=ur.role_id AND u.user_account=?" ;
  29. return   this .getSimpleJdbcTemplate().query(sql,
  30. BeanPropertyRowMapper.newInstance(Role.class ), userName);
  31. }
  32. /**
  33. * 定义UserMapper
  34. */
  35. protected   class  UserMapper  implements  RowMapper<User> {
  36. public  User mapRow(ResultSet rs,  int  rowNum)  throws  SQLException {
  37. User user = new  User();
  38. user.setId(rs.getInt("id" ));
  39. user.setUser_account(rs.getString("user_account" ));
  40. user.setUser_password(rs.getString("user_password" ));
  41. user.setUser_enabled(rs.getInt("user_enabled" ));
  42. user.setUser_desc(rs.getString("user_desc" ));
  43. // 调用上面的方法获取用户所有的权限
  44. user.setRoles(getRolesByUserID(rs.getString("user_account" )));
  45. return  user;
  46. }
  47. }
  48. }

 

Java代码  收藏代码

  1. package  com.spring.security.dao.impl;
  2. import  java.sql.ResultSet;
  3. import  java.sql.SQLException;
  4. import  java.util.List;
  5. import  org.springframework.jdbc.core.RowMapper;
  6. import  org.springframework.stereotype.Repository;
  7. import  com.spring.security.dao.ResourceDao;
  8. import  com.spring.security.dao.support.SimpleDaoSupport;
  9. import  com.spring.security.domain.Resource;
  10. import  com.spring.security.domain.Role;
  11. @Repository ( "resourceDao" )
  12. public   class  ResourceDaoImpl  extends  SimpleDaoSupport  implements  ResourceDao {
  13. @Override
  14. public  List<Resource> getAllResource() {
  15. List<Resource> list = null ;
  16. String sql = "SELECT * from pub_resources" ;
  17. list = this .getSimpleJdbcTemplate().query(sql,  new  RowMapper<Resource>() {
  18. public  Resource mapRow(ResultSet rs,  int  arg1)  throws  SQLException {
  19. Resource resource = new  Resource();
  20. resource.setId(rs.getInt("id" ));
  21. resource.setResource_name(rs.getString("resource_name" ));
  22. resource.setResource_type(rs.getString("resource_type" ));
  23. resource.setResource_string(rs.getString("resource_string" ));
  24. resource.setResource_enabled(rs.getString("resource_enabled" ));
  25. resource.setResource_desc(rs.getString("resource_desc" ));
  26. resource.setRoles(getRoleByResourceId(resource.getId()));
  27. return  resource;
  28. }
  29. });
  30. return  list;
  31. }
  32. private  List<Role> getRoleByResourceId( int  id) {
  33. String sql = "SELECT r.id,r.role_name,r.role_enabled,r.role_desc FROM pub_roles r,pub_roles_resources rr WHERE rr.role_id=r.id AND rr.resource_id=?" ;
  34. return   this .getSimpleJdbcTemplate().query(sql,  new  RowMapper<Role>() {
  35. public  Role mapRow(ResultSet rs,  int  arg1)  throws  SQLException {
  36. Role role = new  Role();
  37. role.setId(rs.getInt("id" ));
  38. role.setRole_name(rs.getString("role_name" ));
  39. role.setRole_enabled(rs.getInt("role_enabled" ));
  40. role.setRole_desc(rs.getString("role_desc" ));
  41. return  role;
  42. }
  43. }, new  Object[] { id });
  44. }
  45. }

 

5 spring security的配置如下:

Xml代码  收藏代码

  1. <? xml   version = "1.0"   encoding = "UTF-8" ?>
  2. < beans:beans   xmlns = "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.1.xsd">
  8. < global-method-security   pre-post-annotations = "enabled"   />
  9. <!--对登录页面不进行拦截,在页面后面加*表示,该页面后面可能会带一些参数 -->
  10. < http   pattern = "/login.jsp*"   security = "none"   />
  11. < http   pattern = "/common/**"   security = "none"   />
  12. < http   pattern = "/js/**"   security = "none"   />
  13. <!-- 保护应用程序配置一些列的权限问题,当没有权限403返回页面为403.jsp -->
  14. < http   auto-config = "true"   access-denied-page = "/common/403.jsp"   use-expressions = "true" >
  15. <!-- login-page: 指定登录页面,并指定默认的target访问地址index.jsp -->
  16. < form-login   login-page = "/login.jsp"   default-target-url = '/index.jsp'   always-use-default-target = 'true'   />
  17. <!-- 配置用户退出的默认返回页面 -->
  18. < logout   logout-success-url = "/login.jsp"   />
  19. <!-- 会话管理配置 ,设置最多登录一次,二次登录会让第一次登录失效,
  20. 则设置error-if-maximum-exceeded为false,要求第一次有效设置为true -->
  21. < session-management   invalid-session-url = "/common/timeout.jsp" >
  22. < concurrency-control   max-sessions = "1"   error-if-maximum-exceeded = "false"   />
  23. </ session-management >
  24. <!-- 将自己的过滤器加入到过滤器链中, 放在FILTER_SECURITY_INTERCEPTOR之前 -->
  25. < custom-filter   ref = "customFilterSecurityInterceptor"   before = "FILTER_SECURITY_INTERCEPTOR"   />
  26. </ http >
  27. <!-- 配置自己的拦截器 -->
  28. < beans:bean   id = "customFilterSecurityInterceptor"
  29. class = "com.spring.security.service.impl.CustomFilterSecurityInterceptorImpl" >
  30. < beans:property   name = "authenticationManager"   ref = "autheticationManager" />
  31. < beans:property   name = "accessDecisionManager"   ref = "customAccessDecisionManager"   />
  32. <!-- resourceService在applicationContext.xml中定义 -->
  33. < beans:property   name = "securityMetadataSource"   ref = "customInvocationSecurityMetadataSource"   />
  34. </ beans:bean >
  35. <!--配置认证管理器 -->
  36. < authentication-manager   alias = "autheticationManager" >
  37. <!-- 使用自定义UserDetailsService -->
  38. < authentication-provider   user-service-ref = "customUserDetailsService" >
  39. < password-encoder   hash = "md5" />
  40. </ authentication-provider >
  41. </ authentication-manager >
  42. < beans:bean   id = "webPrivilegeEvaluator"   class = "org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator" >
  43. < beans:constructor-arg   ref = "customFilterSecurityInterceptor" />
  44. </ beans:bean >
  45. <!-- Jcaptcha相关的配置 -->
  46. < beans:bean   id = "captchaService"    class = "com.octo.captcha.service.image.DefaultManageableImageCaptchaService" >
  47. < beans:property   name = "captchaEngine" >
  48. < beans:bean   class = "com.spring.security.jcaptcha.GMailEngine"   />
  49. </ beans:property >
  50. <!-- 默认生成的图片180秒过期 , 可另行设置 -->
  51. < beans:property   name = "minGuarantedStorageDelayInSeconds"   value = "180"   />
  52. </ beans:bean >
  53. </ beans:beans >

 

Xml代码  收藏代码

  1. <? xml   version = "1.0"   encoding = "UTF-8" ?>
  2. < web-app   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns = "http://java.sun.com/xml/ns/javaee"   xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  4. xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  5. id = "WebApp_ID"   version = "2.5" >
  6. < display-name > springSecurityIII </ display-name >
  7. < context-param >
  8. < param-name > log4jConfigLocation </ param-name >
  9. < param-value > classpath:log4j.xml </ param-value >
  10. </ context-param >
  11. < context-param >
  12. < param-name > log4jRefreshInterval </ param-name >
  13. < param-value > 60000 </ param-value >
  14. </ context-param >
  15. < context-param >
  16. < param-name > contextConfigLocation </ param-name >
  17. < param-value > classpath:applicationContext.xml </ param-value >
  18. </ context-param >
  19. < listener >
  20. < listener-class > org.springframework.web.util.Log4jConfigListener </ listener-class >
  21. </ listener >
  22. < listener >
  23. < listener-class > org.springframework.web.context.ContextLoaderListener </ listener-class >
  24. </ listener >
  25. < listener >
  26. < listener-class > org.springframework.web.util.IntrospectorCleanupListener </ listener-class >
  27. </ listener >
  28. < filter >
  29. < filter-name > CharacterEncodingFilter </ filter-name >
  30. < filter-class > org.springframework.web.filter.CharacterEncodingFilter </ filter-class >
  31. < init-param >
  32. < param-name > encoding </ param-name >
  33. < param-value > UTF-8 </ param-value >
  34. </ init-param >
  35. < init-param >
  36. < param-name > forceEncoding </ param-name >
  37. < param-value > true </ param-value >
  38. </ init-param >
  39. </ filter >
  40. < filter-mapping >
  41. < filter-name > CharacterEncodingFilter </ filter-name >
  42. < url-pattern > /* </ url-pattern >
  43. </ filter-mapping >
  44. < session-config >
  45. < session-timeout > 30 </ session-timeout >
  46. </ session-config >
  47. <!-- JCaptcha`s filter -->
  48. < filter >
  49. < filter-name > jcaptchaFilter </ filter-name >
  50. < filter-class > com.spring.security.jcaptcha.JCaptchaFilter </ filter-class >
  51. < init-param >
  52. < param-name > failureUrl </ param-name >
  53. < param-value > /login.jsp </ param-value >
  54. </ init-param >
  55. </ filter >
  56. <!-- jcaptcha图片生成URL. -->
  57. < filter-mapping >
  58. < filter-name > jcaptchaFilter </ filter-name >
  59. < url-pattern > /jcaptcha.jpg </ url-pattern >
  60. </ filter-mapping >
  61. <!-- jcaptcha登录表单处理URL. 必须放在springSecurityFilter的filter-mapping定义之前 -->
  62. < filter-mapping >
  63. < filter-name > jcaptchaFilter </ filter-name >
  64. < url-pattern > /j_spring_security_check </ url-pattern >
  65. </ filter-mapping >
  66. < filter >
  67. < filter-name > springSecurityFilterChain </ filter-name >
  68. < filter-class > org.springframework.web.filter.DelegatingFilterProxy </ filter-class >
  69. </ filter >
  70. < filter-mapping >
  71. < filter-name > springSecurityFilterChain </ filter-name >
  72. < url-pattern > /* </ url-pattern >
  73. </ filter-mapping >
  74. < listener >
  75. < listener-class > org.springframework.security.web.session.HttpSessionEventPublisher </ listener-class >
  76. </ listener >
  77. < welcome-file-list >
  78. < welcome-file > index.jsp </ welcome-file >
  79. </ welcome-file-list >
  80. </ web-app >

 

 

 

6、其他页面保持不变,进行访问页面如下:

 


 

 admin用户点击admin页面


 切换user用户登入页面进入

 


 点击admin页面,用户访问被拒绝

总结: 这种方法虽然将用户、角色、资源存放到数据库中,但spring security 中<sec:authorize url> tag 的隐藏功能消失,这需要自己去定义类似标签去自行控制。

 

要想在真正在企业中做到很好的控制,其设计会更复杂,下面是基于RBAC设计的数据库

 

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。