之前已经在我的博客中发过security的执行流程图了,大家能够先去看看那个图再看这篇。今天我主要在这里贴出了security配置中的几个重要的类和两个xml配置文件,基本上控制权限的就是这几个文件了。由于近期都比較忙,一直没有时间发出来,导致有点忘记配置时的过程了,所以忘记了一些细节的内容,原本我打算写的具体一点的,但如今都有点忘记了,我在这里就不再一一写出来了,由于在每一个文件的方法或配置里,我用凝视说明了一些配置时所遇到的问题,大家能够看看,可能比較难看,由于表达可能不是非常好,有些写得比較具体,导致非常乱。假设大家有在网上搜索这类文章,基本上大多数配置都是差点儿相同的,这在此之前也在网上參考了几篇文章,都写的不错,我也是參考那里配置的。我给出我看过的几个网址出来,大家能够也去看看:

1、http://wenku.baidu.com/view/ba1f791aff00bed5b9f31dc1.html 我数据库是在这篇里取的

2、http://blog.csdn.net/k10509806/article/details/6436987

3、http://johnny-lee.iteye.com/blog/1701126

4、http://blog.csdn.net/k10509806/article/details/6369131

依照第4篇的配置基本上都是能配置出来的

另一个须要说明的是,在applicationContext-security.xml里我凝视掉了

auto-config="true"

这个配置比較重要的,假设你不配置,security可能不会启动,我为什么又把它凝视掉了,是由于当你配置了自己主动义的登录页面,就不用这个了,这个的作用可能是在项目启动时,假设你没有自己定义的登录页面,它就会跳转到security默认的登录页面中。

我把我配置的项目放上来,大家能够去下载,我也就赚点积分,常在CSDN混,不能没有积分啊,望大家理解,下载地址:

http://download.csdn.net/detail/u011511684/7597101



事实上之前我也上传了一个上去了,可是那个配置好像不是非常完整。

我的项目是用maven搭建的,假设你配置了maven,那么就能够非常轻松的执行起项目来了,

步骤:

1、在我的项目下找到database目录,把里面的union_ssh.sql文件导入到mysql数据库中

2、导入项目SSHMS到myEclipse中

3、在myEclipse中使用maven install,执行后,可能会稍等一下,由于它在连网下载jar包,这样就不用自己去下载jar包了

4、执行后,在登录页面输入账号、passwordadmin就能够登录到主界面去了,这个账号的权限是能够訪问树中的全部页面;也能够使用账号、passwordtest登录,但这个账号权限仅仅能用户管理这个页面

web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  3. <display-name></display-name>
  4.  
  5. <!-- spring配置文件位置 -->
  6. <context-param>
  7. <param-name>contextConfigLocation</param-name>
  8. <param-value>classpath:spring.xml,classpath:spring-hibernate.xml,classpath:applicationContext-security.xml</param-value>
  9. </context-param>
  10.  
  11. <!-- spring security 过滤器, 这个的位置顺序和spring的监听器启动位置没有什么关系,能够放在spring监听器的前面,也能够放置在后面。
  12. 但一定要放在struts的过滤器前面,由于假设有自己定义的登录页面,当登录时,就会跳转到了struts相应的action中,
  13. 导致无法使用spring security的验证登录了,正常情况下,应该登录时,会经过自己定义的MyUsernamePasswordAuthenticationFilter类的attemptAuthentication方法进行验证。
  14. 假设验证成功,则登录成功,不再运行相应的action验证登录 ;spring security验证失败,则跳回指定登录失败的页面。
  15. -->
  16. <filter>
  17. <filter-name>springSecurityFilterChain</filter-name>
  18. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  19. </filter>
  20. <filter-mapping>
  21. <filter-name>springSecurityFilterChain</filter-name>
  22. <url-pattern>/*</url-pattern>
  23. </filter-mapping>
  24.  
  25. <!-- spring监听器 -->
  26. <listener>
  27. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  28. </listener>
  29.  
  30. <!-- hibernate配置 -->
  31. <filter>
  32. <filter-name>openSessionInViewFilter</filter-name>
  33. <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
  34. <init-param>
  35. <param-name>singleSession</param-name>
  36. <param-value>true</param-value>
  37. </init-param>
  38. </filter>
  39.  
  40. <!-- Struts2配置 -->
  41. <filter>
  42. <filter-name>struts2</filter-name>
  43. <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  44. </filter>
  45. <!-- hibernate的session启动过滤器,在url请求action时启动 ,不配置这个,url请求时无法启动hibernate的session-->
  46. <filter-mapping>
  47. <filter-name>openSessionInViewFilter</filter-name>
  48. <url-pattern>/*</url-pattern>
  49. </filter-mapping>
  50. <!-- struts拦截的url后缀 -->
  51. <filter-mapping>
  52. <filter-name>struts2</filter-name>
  53. <url-pattern>*.action</url-pattern>
  54. <url-pattern>*.jsp</url-pattern>
  55. <url-pattern>*.html</url-pattern>
  56. </filter-mapping>
  57.  
  58. <welcome-file-list>
  59. <welcome-file>/login.jsp</welcome-file>
  60. </welcome-file-list>
  61. </web-app>

applicationContext-security.xml,security的主要配置文件

  1. <beans:beans xmlns="http://www.springframework.org/schema/security"
  2. xmlns:beans="http://www.springframework.org/schema/beans"
  3. 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.xsd">
  8.  
  9. <!-- No bean named 'springSecurityFilterChain' is defined
  10. 1、 这时公布一下你的项目,查看tomcat的webapps目录下,找到你的项目目录的classes目录有没有相关的spring.xml文件存在,不存在就会报错
  11. 2、查看web.xml文件<param-value>标签有没有引入applicationContext-security.xml这个文件
  12. -->
  13.  
  14. <!-- 不用经过spring security过滤,一般js、css都不须要过滤 -->
  15.  
  16. <http pattern="/*/js/**" security="none"/>
  17. <http pattern="/common/js/**" security="none"/>
  18. <http pattern="/login.jsp" security="none"/>
  19. <http pattern="/login_logo.jpg" security="none"/>
  20.  
  21. <!-- auto-config="true" -->
  22. <http use-expressions="true" entry-point-ref="authenticationProcessingFilterEntryPoint" >
  23. <!-- 不再在这里对url进行权限拦截,在数据库中取出url中相应的权限
  24. <intercept-url pattern="/**" access="ROLE_USER" />
  25. -->
  26. <!-- 单用户登陆 -->
  27. <session-management>
  28. <concurrency-control max-sessions="1"
  29. error-if-maximum-exceeded="true" />
  30. </session-management>
  31.  
  32. <!-- 这样的自己定义的登录页面,不能经过security的用户信息验证,也就等于不能取出用户的权限
  33. <form-login login-page='/login.jsp' default-target-url="/index.jsp"/>
  34. -->
  35. <!-- 尝试訪问没有权限的页面时跳转的页面 -->
  36. <access-denied-handler error-page="/403.jsp"/>
  37.  
  38. <custom-filter ref="loginFilter" position="FORM_LOGIN_FILTER" />
  39.  
  40. <custom-filter ref="myFilter" before="FILTER_SECURITY_INTERCEPTOR"/>
  41.  
  42. <!-- 检測失效的sessionId,session超时时,定位到另外一个URL -->
  43. <session-management invalid-session-url="/sessionTimeOut.jsp" />
  44. <!--
  45. <custom-filter ref="logoutFilter" before="LOGOUT_FILTER"/>
  46. -->
  47.  
  48. <logout invalidate-session="true" logout-success-url="/" logout-url="/logout"/>
  49. </http>
  50.  
  51. <!-- 登录验证器 -->
  52. <beans:bean id="loginFilter"
  53. class="framework.security.login.MyUsernamePasswordAuthenticationFilter">
  54.  
  55. <!-- value="/loginUser.action"处理登录表单的action ,value值要以“/”开关,否则会报错 :
  56. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.filterChains': Cannot resolve reference to bean 'org.springframework.security.web.DefaultSecurityFilterChain#3' while setting bean property 'sourceList' with key [3]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.DefaultSecurityFilterChain#3': Cannot resolve reference to bean 'loginFilter' while setting constructor argument with key [4]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginFilter' defined in class path resource [applicationContext-security.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
  57. PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'filterProcessesUrl' threw exception; nested exception is java.lang.IllegalArgumentException: userAction!login.action isn't a valid redirect URL
  58. -->
  59. <beans:property name="filterProcessesUrl" value="/user/loginUser.action"></beans:property>
  60. <!-- 验证成功后的处理 -->
  61. <beans:property name="authenticationSuccessHandler" ref="loginLogAuthenticationSuccessHandler"></beans:property>
  62.  
  63. <!-- 验证失败后的处理 -->
  64. <beans:property name="authenticationFailureHandler" ref="simpleUrlAuthenticationFailureHandler"></beans:property>
  65.  
  66. <beans:property name="authenticationManager" ref="authenticationManager"></beans:property>
  67.  
  68. <!-- 注入DAO为了查询相应的用户 -->
  69. <beans:property name="userDao" ref="userDao"></beans:property>
  70. </beans:bean>
  71.  
  72. <beans:bean id="loginLogAuthenticationSuccessHandler"
  73. class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
  74. <beans:property name="defaultTargetUrl" value="/index.jsp"></beans:property>
  75. </beans:bean>
  76.  
  77. <beans:bean id="simpleUrlAuthenticationFailureHandler"
  78. class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
  79. <!-- 能够配置相应的跳转方式。属性forwardToDestination为true採用forward false为sendRedirect -->
  80. <beans:property name="defaultFailureUrl" value="/login.jsp"></beans:property>
  81. </beans:bean>
  82.  
  83. <!-- 认证过滤器 -->
  84. <beans:bean id="myFilter" class="framework.security.base.MyFilterSecurityInterceptor">
  85.  
  86. <beans:property name="authenticationManager" ref="authenticationManager" />
  87.  
  88. <beans:property name="accessDecisionManager" ref="myAccessDecisionManagerBean" />
  89.  
  90. <beans:property name="securityMetadataSource" ref="mySecurityMetadataSource" />
  91. </beans:bean>
  92.  
  93. <!-- spring security提供的用户登录验证 ,alias的值相应上面的ref="authenticationManager" -->
  94. <authentication-manager alias="authenticationManager">
  95. <!--userDetailServiceImpl 获取登录的用户、用户权限 -->
  96. <authentication-provider user-service-ref="userDetailServiceImpl" />
  97.  
  98. </authentication-manager>
  99.  
  100. <!-- 获取登录的用户、用户权限 -->
  101. <beans:bean id="userDetailServiceImpl" class="framework.security.base.MyUserDetailsService">
  102. <beans:property name="userDao" ref="userDao"></beans:property>
  103. </beans:bean>
  104.  
  105. <!-- 推断是否有权限訪问请求的url页面 -->
  106.  
  107. <beans:bean id="myAccessDecisionManagerBean"
  108. class="framework.security.base.MyAccessDecisionManager">
  109. </beans:bean>
  110.  
  111. <!-- 获取数据库中全部的url资源,读出url资源与权限的相应关系 -->
  112.  
  113. <beans:bean id="mySecurityMetadataSource"
  114. class="framework.security.base.MySecurityMetadataSource">
  115. </beans:bean>
  116.  
  117. <!-- 未登录的切入点 -->
  118. <beans:bean id="authenticationProcessingFilterEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
  119. <beans:property name="loginFormUrl" value="/sessionTimeOut.jsp"></beans:property>
  120. </beans:bean>
  121.  
  122. </beans:beans>

MySecurityMetadataSource类,负责读取数据库中的url相应的权限

  1. package framework.security.base;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collection;
  5. import java.util.HashMap;
  6. import java.util.Iterator;
  7. import java.util.List;
  8. import java.util.Map;
  9.  
  10. import org.hibernate.Query;
  11. import org.hibernate.Session;
  12. import org.hibernate.SessionFactory;
  13. import org.springframework.context.ApplicationContext;
  14. import org.springframework.context.support.ClassPathXmlApplicationContext;
  15. import org.springframework.security.access.ConfigAttribute;
  16. import org.springframework.security.access.SecurityConfig;
  17. import org.springframework.security.web.FilterInvocation;
  18. import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
  19.  
  20. import com.user.dao.UserDaoI;
  21.  
  22. import framework.security.util.UrlPathMatcher;
  23.  
  24. //1、2、3、4是server启动时调用的顺序
  25. public class MySecurityMetadataSource implements
  26. FilterInvocationSecurityMetadataSource {
  27.  
  28. /*
  29. *resourceMap用static声明了,为了避免用户每请求一次都要去数据库读取资源、权限,这里仅仅读取一次,将它保存起来
  30. */
  31. private static Map<String, Collection<ConfigAttribute>> resourceMap = null;
  32.  
  33. private UrlPathMatcher urlMatcher = new UrlPathMatcher();
  34.  
  35. private UserDaoI userDao;
  36.  
  37. // 1
  38. //构造函数,由于server启动时会调用这个类,利用构造函数读取全部的url、角色
  39. public MySecurityMetadataSource() {
  40.  
  41. //初始化,读取数据库全部的url、角色
  42. loadResourceDefine();
  43. }
  44.  
  45. //2
  46. //这种方法应该是要从数据库读取数据的,这里仅仅用来測试
  47. /*private void loadResourceDefine() {
  48.  
  49. System.out.println("metadata : loadResourceDefine");
  50. resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
  51. Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
  52.  
  53. *//**
  54. * 将这里的new SecurityConfig("ROLE_ADMIN")值改为ROLE_USER,登录成功也不同意訪问index.jsp了,
  55. * 由于在applicationContext-security.xml设置了仅仅同意角色为ROLE_ADMIN的訪问。
  56. * <intercept-url pattern="/**" access="ROLE_ADMIN" />
  57. *//*
  58. ConfigAttribute ca = new SecurityConfig("ROLE_ADMIN");
  59. atts.add(ca);
  60.  
  61. //ca为訪问的权限,以下为url地址赋予ca中的权限
  62. resourceMap.put("/i.jsp", atts);
  63. resourceMap.put("/index.jsp", atts);
  64.  
  65. }*/
  66.  
  67. //这种方法在url请求时才会调用,server启动时不会运行这种方法,前提是须要在<http>标签内设置 <custom-filter>标签
  68. //getAttributes这种方法会依据你的请求路径去获取这个路径应该是有哪些权限才干够去訪问。
  69. @Override
  70. public Collection<ConfigAttribute> getAttributes(Object object)
  71. throws IllegalArgumentException {
  72.  
  73. //object getRequestUrl 是获取用户请求的url地址
  74. String url = ((FilterInvocation) object).getRequestUrl();
  75.  
  76. //resourceMap保存了loadResourceDefine方法载入进来的数据
  77. Iterator<String> ite = resourceMap.keySet().iterator();
  78.  
  79. while (ite.hasNext()) {
  80.  
  81. //取出resourceMap中读取数据库的url地址
  82. String resURL = ite.next();
  83.  
  84. //假设两个 url地址同样,那么将返回resourceMap中相应的权限集合,然后跳转到MyAccessDecisionManager类里的decide方法,再推断权限
  85. if (urlMatcher.pathMatchesUrl(url, resURL)) {
  86. return resourceMap.get(resURL); //返回相应的url地址的权限 ,resourceMap是一个主键为地址,值为权限的集合对象
  87. }
  88. }
  89.  
  90. //假设上面的两个url地址没有匹配,返回return null,不再调用MyAccessDecisionManager类里的decide方法进行权限验证,代表同意訪问页面
  91. return null;
  92. }
  93.  
  94. // 4
  95. @Override
  96. public Collection<ConfigAttribute> getAllConfigAttributes() {
  97.  
  98. return null;
  99. }
  100.  
  101. // 3
  102. @Override
  103. public boolean supports(Class<?> clazz) {
  104.  
  105. return true;
  106.  
  107. }
  108.  
  109. private void loadResourceDefine() {
  110.  
  111. //请注意这里读取了spring的xml配置文件,假设改变了spring的xml文件名,这里也要改变的
  112. ApplicationContext context=new ClassPathXmlApplicationContext(new String[]{"classpath:spring.xml","classpath:spring-hibernate.xml"});
  113.  
  114. SessionFactory sessionFactory = (SessionFactory) context
  115. .getBean("sessionFactory");
  116.  
  117. Session session=(Session) sessionFactory.openSession();
  118.  
  119. // 提取系统中的全部权限。
  120. List<String> auNames =session.createQuery("select roleName from PubRoles").list();
  121.  
  122. session.close();//取数后将session关闭
  123.  
  124. resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
  125.  
  126. for (String auth : auNames) {
  127. ConfigAttribute ca = new SecurityConfig(auth);
  128.  
  129. //查出相应的角色的资源
  130. Query query1=sessionFactory.openSession().createSQLQuery("SELECT resource_string FROM pub_resources WHERE resource_id IN (SELECT resource_id FROM pub_authorities_resources WHERE authority_id IN (SELECT authority_id FROM pub_roles_authorities WHERE role_id =( SELECT role_id FROM pub_roles WHERE role_name='"+auth+"')))");
  131.  
  132. List<String> list = query1.list();
  133.  
  134. for (String res : list) {
  135. String url = res;
  136.  
  137. // * 推断资源文件和权限的相应关系,假设已经存在相关的资源url,则要通过该url为key提取出权限集合,将权限添加�到权限集合中。
  138. if (resourceMap.containsKey(url)) {
  139.  
  140. Collection<ConfigAttribute> value = resourceMap.get(url); //取出这个url的权限集合
  141. value.add(ca);
  142. resourceMap.put(url, value);
  143. } else {
  144. Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
  145. atts.add(ca);
  146. resourceMap.put(url, atts);
  147. }
  148. }
  149. }
  150. }
  151.  
  152. public UserDaoI getUserDao() {
  153. return userDao;
  154. }
  155.  
  156. public void setUserDao(UserDaoI userDao) {
  157. this.userDao = userDao;
  158. }
  159.  
  160. }

MyFilterSecurityInterceptor类,负责过滤url请求

  1. package framework.security.base;
  2.  
  3. import java.io.IOException;
  4.  
  5. import javax.servlet.Filter;
  6. import javax.servlet.FilterChain;
  7. import javax.servlet.FilterConfig;
  8. import javax.servlet.ServletException;
  9. import javax.servlet.ServletRequest;
  10. import javax.servlet.ServletResponse;
  11.  
  12. import org.springframework.security.access.SecurityMetadataSource;
  13. import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
  14. import org.springframework.security.access.intercept.InterceptorStatusToken;
  15. import org.springframework.security.web.FilterInvocation;
  16. import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
  17.  
  18. //implements Filter是servlet的filter类
  19. public class MyFilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter {
  20.  
  21. private FilterInvocationSecurityMetadataSource securityMetadataSource;
  22.  
  23. @Override
  24. public void destroy() {
  25. // TODO Auto-generated method stub
  26. }
  27.  
  28. @Override
  29. public void doFilter(ServletRequest arg0, ServletResponse arg1,
  30. FilterChain arg2) throws IOException, ServletException {
  31.  
  32. FilterInvocation fi = new FilterInvocation(arg0, arg1, arg2);
  33. invoke(fi);
  34.  
  35. }
  36.  
  37. @Override
  38. public void init(FilterConfig arg0) throws ServletException {
  39. // TODO Auto-generated method stub
  40.  
  41. }
  42.  
  43. @Override
  44. public Class<?> getSecureObjectClass() {
  45. return FilterInvocation.class;
  46. }
  47.  
  48. @Override
  49. public SecurityMetadataSource obtainSecurityMetadataSource() {
  50. return this.securityMetadataSource;
  51. }
  52.  
  53. //自己定义的方法
  54. public void invoke(FilterInvocation fi) throws IOException, ServletException {
  55.  
  56. InterceptorStatusToken token = super.beforeInvocation(fi);
  57.  
  58. try {
  59. fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
  60. } finally {
  61. super.afterInvocation(token, null);
  62. }
  63. }
  64.  
  65. public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
  66. return securityMetadataSource;
  67. }
  68.  
  69. public void setSecurityMetadataSource(
  70. FilterInvocationSecurityMetadataSource securityMetadataSource) {
  71.  
  72. this.securityMetadataSource = securityMetadataSource;
  73. }
  74.  
  75. }

MyUserDetailsService类,用户登录验证的类

  1. package framework.security.base;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collection;
  5. import java.util.HashSet;
  6. import java.util.List;
  7. import java.util.Set;
  8.  
  9. import org.springframework.security.access.AccessDeniedException;
  10. import org.springframework.security.core.GrantedAuthority;
  11. import org.springframework.security.core.userdetails.User;
  12. import org.springframework.security.core.userdetails.UserDetails;
  13. import org.springframework.security.core.userdetails.UserDetailsService;
  14. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  15. import org.springframework.security.core.userdetails.memory.UserMap;
  16.  
  17. import com.user.dao.UserDaoI;
  18. import com.user.dao.impl.UserDaoImpl;
  19. import com.user.model.PubUsers;
  20.  
  21. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  22.  
  23. import org.springframework.security.core.authority.GrantedAuthorityImpl;
  24.  
  25. public class MyUserDetailsService implements UserDetailsService{
  26.  
  27. private UserDaoImpl userDao;
  28.  
  29. @Override
  30. public UserDetails loadUserByUsername(String username)
  31. throws UsernameNotFoundException {
  32.  
  33. Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
  34.  
  35. PubUsers users=userDao.userInfo(username);
  36. /* if(users.getAccount()==null){
  37. throw new AccessDeniedException("账号或password错误!");
  38. }*/
  39.  
  40. /*不要使用GrantedAuthorityImpl,官网说这个已过期了,
  41. * SimpleGrantedAuthority取代GrantedAuthorityImpl,赋予一个角色(即权限)
  42. *
  43. * */
  44. List<String> list = userDao.findAuthByUsername(username);
  45. for (int i = 0; i < list.size(); i++) {
  46.  
  47. auths.add(new SimpleGrantedAuthority(list.get(i)));
  48. //auths.add(new GrantedAuthorityImpl(list.get(i)));
  49.  
  50. }
  51.  
  52. boolean enables = true;
  53. boolean accountNonExpired = true;
  54. boolean credentialsNonExpired = true;
  55. boolean accountNonLocked = true;
  56.  
  57. //System.out.println(users.getUserName());
  58. //System.out.println(users.getUserPassword());
  59.  
  60. //封装成spring security的User
  61. User userdetail = new User(users.getUserAccount(), users.getUserPassword(), enables, accountNonExpired, credentialsNonExpired, accountNonLocked, auths);
  62.  
  63. return userdetail;
  64. }
  65.  
  66. public UserDaoImpl getUserDao() {
  67. return userDao;
  68. }
  69.  
  70. public void setUserDao(UserDaoImpl userDao) {
  71. this.userDao = userDao;
  72. }
  73.  
  74. }

MyAccessDecisionManager类,负责权限的控制,假设请求的url在权限集合中有这个url相应的值,则放行。注:假设数据库中没有对这个url定义訪问的权限,默认是会被放行的

  1. package framework.security.base;
  2.  
  3. import java.util.Collection;
  4. import java.util.Iterator;
  5.  
  6. import org.springframework.security.access.AccessDecisionManager;
  7. import org.springframework.security.access.AccessDeniedException;
  8. import org.springframework.security.access.ConfigAttribute;
  9. import org.springframework.security.access.SecurityConfig;
  10. import org.springframework.security.authentication.InsufficientAuthenticationException;
  11. import org.springframework.security.core.Authentication;
  12. import org.springframework.security.core.GrantedAuthority;
  13.  
  14. public class MyAccessDecisionManager implements AccessDecisionManager {
  15.  
  16. //In this method, need to compare authentication with configAttributes.
  17. // 1, A object is a URL, a filter was find permission configuration by this URL, and pass to here.
  18. // 2, Check authentication has attribute in permission configuration (configAttributes)
  19. // 3, If not match corresponding authentication, throw a AccessDeniedException.
  20.  
  21. //这种方法在url请求时才会调用,server启动时不会运行这种方法,前提是须要在<http>标签内设置 <custom-filter>标签
  22. /*
  23. * 參数说明:
  24. * 1、configAttributes 装载了请求的url同意的角色数组 。这里是从MySecurityMetadataSource里的loadResourceDefine方法里的atts对象取出的角色数据赋予给了configAttributes对象
  25. * 2、authentication 装载了从数据库读出来的角色 数据。这里是从MyUserDetailsService里的loadUserByUsername方法里的auths对象的值传过来给 authentication 对象
  26. *
  27. * */
  28. @Override
  29. public void decide(Authentication authentication, Object object,
  30. Collection<ConfigAttribute> configAttributes)
  31. throws AccessDeniedException, InsufficientAuthenticationException {
  32.  
  33. /*
  34. * authentication装载了用户的信息数据,当中有角色。是MyUserDetailsService里的loadUserByUsername方法的userdetail对象传过来的
  35. * userdetail一共同拥有7个參数(以下打印出来的数据可相应一下security的User类,这个类能够看到有寻7个參数),
  36. * 最后一个是用来保存角色数据的,假设角色为空,将无权訪问页面。
  37. * 看到以下的打印数据, Granted Authorities: ROLE_ADMIN,ROLE_ADMIN 就是角色了。
  38. * 假设显示Not granted any authorities,则说明userdetail的最后一个參数为空,没有传送角色的值过来
  39. *
  40. * 打印出的数据:
  41. * auth:org.springframework.security.authentication.UsernamePasswordAuthenticationToken@bf5fbace:
  42. Principal: org.springframework.security.core.userdetails.User@c20:
  43. Username: aa;
  44. Password: [PROTECTED];
  45. Enabled: true;
  46. AccountNonExpired: true;
  47. credentialsNonExpired: true;
  48. AccountNonLocked: true;
  49. Granted Authorities: ROLE_ADMIN;
  50. Credentials: [PROTECTED];
  51. Authenticated: true;
  52. Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffc7f0c: RemoteIpAddress: 127.0.0.1;
  53. SessionId: 0952B3F9F18222DCCD0ECE39D039F900;
  54. Granted Authorities: ROLE_ADMIN
  55. */
  56.  
  57. if(configAttributes == null){
  58. return;
  59. }
  60. //System.out.println(object.toString()); //object is a URL.
  61.  
  62. Iterator<ConfigAttribute> ite=configAttributes.iterator();
  63. while(ite.hasNext()){
  64.  
  65. ConfigAttribute ca=ite.next();
  66. String needRole=((SecurityConfig)ca).getAttribute();
  67.  
  68. for(GrantedAuthority ga:authentication.getAuthorities()){
  69. //推断两个请求的url页面的权限和用户的权限是否同样,如同样,同意訪问
  70. if(needRole.equals(ga.getAuthority())){
  71.  
  72. /* <intercept-url pattern="/**" access="ROLE_ADMIN" />
  73. * 假设applicationContext-security.xml的http标签里面有这样的配置,
  74. * 在needRole为ROLE_USER时,即使needRole和ga.getAuthority权限匹配了,但权限是ROLE_USER,即使运行了return,
  75. * 还是会无法訪问请求的url页面,由于终于都是以http标签里的权限来拦截,即仅仅能在权限为 ROLE_ADMIN才可訪问
  76. */
  77. return;
  78. }
  79. }
  80. }
  81. //假设上面的needRole和ga.getAuthority两个权限没有匹配,将不同意訪问
  82. throw new AccessDeniedException("Access Denied");
  83.  
  84. }
  85.  
  86. /*
  87. * * 这个 supports(ConfigAttribute attribute) 方法在启动的时候被
  88. * AbstractSecurityInterceptor调用,来决定AccessDecisionManager
  89. * 能否够运行传递ConfigAttribute。 supports(Class)方法被安全拦截器实现调用,
  90. * 包括安全拦截器将显示的AccessDecisionManager支持安全对象的类型。
  91. *
  92. * */
  93. @Override
  94. public boolean supports(ConfigAttribute attribute) {
  95.  
  96. return true;
  97. //return false;
  98. }
  99.  
  100. @Override
  101. public boolean supports(Class<?> clazz) {
  102.  
  103. return true;
  104. //return false;
  105. }
  106.  
  107. }

MyUsernamePasswordAuthenticationFilter类,自己定义的登录类

  1. package framework.security.login;
  2.  
  3. import java.io.IOException;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6.  
  7. import javax.security.auth.login.AccountExpiredException;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. import javax.servlet.http.HttpSession;
  11.  
  12. import org.apache.commons.lang3.StringUtils;
  13. import org.apache.struts2.ServletActionContext;
  14. import org.springframework.security.authentication.AuthenticationServiceException;
  15. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  16. import org.springframework.security.core.Authentication;
  17. import org.springframework.security.core.AuthenticationException;
  18. import org.springframework.security.web.WebAttributes;
  19. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
  20.  
  21. import com.user.dao.UserDaoI;
  22. import com.user.model.PubUsers;
  23.  
  24. import framework.util.MD5Utils;
  25.  
  26. public class MyUsernamePasswordAuthenticationFilter extends
  27. UsernamePasswordAuthenticationFilter {
  28. public static final String VALIDATE_CODE = "validateCode";
  29. public static final String USERNAME = "userAccount";
  30. public static final String PASSWORD = "userPassword";
  31. private int showCheckCode = 0;
  32.  
  33. public int getShowCheckCode() {
  34. return showCheckCode;
  35. }
  36.  
  37. public void setShowCheckCode(int showCheckCode) {
  38. this.showCheckCode = showCheckCode;
  39. }
  40.  
  41. private MD5Utils md5 =new MD5Utils();
  42.  
  43. private UserDaoI userDao;
  44.  
  45. public UserDaoI getUserDao() {
  46. return userDao;
  47. }
  48.  
  49. public void setUserDao(UserDaoI userDao) {
  50. this.userDao = userDao;
  51. }
  52.  
  53. public MD5Utils getMd5() {
  54. return md5;
  55. }
  56.  
  57. public void setMd5(MD5Utils md5) {
  58. this.md5 = md5;
  59. }
  60.  
  61. @Override
  62. public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
  63. if (!request.getMethod().equals("POST")) {
  64. throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
  65. }
  66. //检測验证码
  67. checkValidateCode(request);
  68.  
  69. String username = obtainUsername(request);
  70. String password = obtainPassword(request);
  71.  
  72. //验证用户账号与password是否相应
  73. username = username.trim();
  74.  
  75. PubUsers users=userDao.userInfo(username);
  76.  
  77. HttpSession session = request.getSession();
  78. session = request.getSession(false);//false代表不创建新的session,直接获取当前的session
  79.  
  80. //将用户名存进session,假设登录成功,显示在主页
  81. session.setAttribute("login_account",username);
  82.  
  83. if(users == null) {
  84.  
  85. session.setAttribute("showCheckCode" ,"1" );
  86. session.setAttribute("SECURITY_LOGIN_EXCEPTION" ,
  87. "用户名或password错误!" );
  88.  
  89. throw new AuthenticationServiceException("用户名或password错误!");
  90.  
  91. }else if(users.getUserPassword()=="" || users.getUserPassword()==null){
  92.  
  93. session.setAttribute("showCheckCode" ,"1" );
  94. session.setAttribute("SECURITY_LOGIN_EXCEPTION" ,
  95. "用户名或password错误!" );
  96.  
  97. throw new AuthenticationServiceException("用户名或password错误!");
  98.  
  99. }else if(!users.getUserPassword().equals(md5.MD5Encode(password))){// password加密后再进行验证
  100.  
  101. session.setAttribute("showCheckCode" ,"1" );
  102. session.setAttribute("SECURITY_LOGIN_EXCEPTION" ,
  103. "用户名或password错误!" );
  104.  
  105. throw new AuthenticationServiceException("用户名或password错误!");
  106.  
  107. }else{
  108.  
  109. if(session.getAttribute("showCheckCode")=="1"){
  110. session.setAttribute("showCheckCode" , "0" );
  111. }
  112. }
  113.  
  114. //UsernamePasswordAuthenticationToken实现 Authentication
  115. //这里要注意了,我第二个參数是用自己的md5加密了password再去传參的,由于我的password都是加密后存进数据库的。
  116. //假设这里不加密,那么和在数据库取出来的不匹配,终于即使登录账号和password都正确,也将无法登录成功。
  117. //由于在AbstractUserDetailsAuthenticationProvider里还会对用户和password验证,各自是
  118. //user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);//这个通过才干顺利通过
  119. //还有一个是 additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication);//假设retrieveUser方法验证不通过,将无法訪问
  120. UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, md5.MD5Encode(password));
  121. // Place the last username attempted into HttpSession for views
  122.  
  123. // 同意子类设置具体属性
  124. setDetails(request, authRequest);
  125.  
  126. // 执行UserDetailsService的loadUserByUsername 再次封装Authentication
  127. return this.getAuthenticationManager().authenticate(authRequest);
  128. }
  129.  
  130. protected void checkValidateCode(HttpServletRequest request) {
  131. HttpSession session = request.getSession();
  132.  
  133. String sessionValidateCode = obtainSessionValidateCode(session);
  134.  
  135. if( session.getAttribute("showCheckCode")=="1"){
  136.  
  137. //让上一次的验证码失效
  138. session.setAttribute(VALIDATE_CODE, null);
  139. String validateCodeParameter = obtainValidateCodeParameter(request);
  140.  
  141. //推断输入的验证码和保存在session中的验证码是否同样,这里不区分大写和小写进行验证
  142. if (StringUtils.isEmpty(validateCodeParameter) || !sessionValidateCode.equalsIgnoreCase(validateCodeParameter)) {
  143.  
  144. session = request.getSession(false);//false代表不创建新的session,直接获取当前的session
  145. session.setAttribute("SECURITY_LOGIN_EXCEPTION" ,
  146. "验证码错误" );
  147.  
  148. throw new AuthenticationServiceException("验证码错误!");
  149. }
  150. }
  151. }
  152.  
  153. private String obtainValidateCodeParameter(HttpServletRequest request) {
  154. Object obj = request.getParameter(VALIDATE_CODE);
  155. return null == obj ? "" : obj.toString();
  156. }
  157.  
  158. protected String obtainSessionValidateCode(HttpSession session) {
  159. Object obj = session.getAttribute(VALIDATE_CODE);
  160. return null == obj ? "" : obj.toString();
  161. }
  162.  
  163. @Override
  164. protected String obtainUsername(HttpServletRequest request) {
  165. Object obj = request.getParameter(USERNAME);
  166. return null == obj ? "" : obj.toString();
  167. }
  168.  
  169. @Override
  170. protected String obtainPassword(HttpServletRequest request) {
  171. Object obj = request.getParameter(PASSWORD);
  172. return null == obj ? "" : obj.toString();
  173. }
  174.  
  175. }

spring security3.2配置---权限管理的更多相关文章

  1. Spring Security3详细配置

    Spring Security3详细配置 表名:RESOURCE 解释:资源表备注: 资源表 RESOURCE(资源表) 是否主键 字段名 字段描述 数据类型 长度 可空 约束 缺省值 备注 是 ID ...

  2. Spring Security实现RBAC权限管理

    Spring Security实现RBAC权限管理 一.简介 在企业应用中,认证和授权是非常重要的一部分内容,业界最出名的两个框架就是大名鼎鼎的 Shiro和Spring Security.由于Spr ...

  3. spring的annotation-driven配置事务管理器详解

    http://blog.sina.com.cn/s/blog_8f61307b0100ynfb.html ——————————————————————————————————————————————— ...

  4. spring security3.1配置比较纠结的2个问题

    转自:http://www.iteye.com/topic/1122629 总论无疑问的,spring security在怎么保护网页应用安全上做得很强很周全,但有些地方还是很差强人意,比如对< ...

  5. spring security 登录、权限管理配置

    登录流程 1)容器启动(MySecurityMetadataSource:loadResourceDefine加载系统资源与权限列表)  2)用户发出请求  3)过滤器拦截(MySecurityFil ...

  6. Spring boot整合shiro权限管理

    Apache Shiro功能框架: Shiro聚焦与应用程序安全领域的四大基石:认证.授权.会话管理和保密. #,认证,也叫作登录,用于验证用户是不是他自己所说的那个人: #,授权,也就是访问控制,比 ...

  7. Jenkins配置权限管理

    借鉴博客:https://www.cnblogs.com/Eivll0m/p/6734076.html 懒得写了,照上面是配置成功了,弄了权限角色与用户的配置

  8. Spring boot Security 用于权限管理,用户添加等。

    1:添加依赖: <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thy ...

  9. 使用Spring Security3的四种方法概述

    使用Spring Security3的四种方法概述 那么在Spring Security3的使用中,有4种方法: 一种是全部利用配置文件,将用户.权限.资源(url)硬编码在xml文件中,已经实现过, ...

随机推荐

  1. nexus3添加第三方jar

    最近在看maven的打包及管理,然後就看到nexus,自己在安裝的時候就下載了最新版的nexus-3.2.0-01-win64,按照文档部署后启动,浏览.之前一致使用的是2.0的,所以还是需要导出点点 ...

  2. 集成Facebook和Twitter的Model动画-b

    这个动画.  感谢大神分享 JPPopPresentAnimation.gif 要实现这个功能分两步走:第一步,先实现这个动画.第二步,0行代码集成到项目.也就是,你不用改原有项目的任何代码,只要把写 ...

  3. IEEE会议排名(转载)

    不知道谁整理的,我就下了个word.所以就标注不了,引用的哪的了. Rank 1: SIGCOMM: ACM Conf on Comm Architectures, Protocols & A ...

  4. 构建简单的 C++ 服务组件,第 1 部分: 服务组件体系结构 C++ API 简介

    构建简单的 C++ 服务组件,第 1 部分: 服务组件体系结构 C++ API 简介 熟悉将用于 Apache Tuscany SCA for C++ 的 API.您将通过本文了解该 API 的主要组 ...

  5. 【网络流24题】 No.6 最长不减子序列问题 (最大流)[模型:最多不相交路径]

    [题意] 给定正整数序列x1 ,x2 , x3... ( 1)计算其最长不减子序列的长度 s.( 2)计算从给定的序列中最多可取出多少个长度为 s 的不减子序列.( 3) 如果允许在取出的序列中多次使 ...

  6. Android Training精要(六)如何防止Bitmap对象出现OOM

    1.使用AsyncTask異步加載bitmap圖片避免OOM: class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> ...

  7. 【CF】283D Tennis Game

    枚举t加二分判断当前t是否可行,同时求出s.注意不能说|a[n]| <= |3-a[n]|就证明无解,开始就是wa在这儿了.可以简单想象成每当a[n]赢的时候,两人都打的难解难分(仅多赢一轮): ...

  8. wcf异常汇总

    1.确保客户端可以接收到服务端的异常 2.部署wcf出错,http错误404.3 3.无法自动调试 未能调试远程过程.这通常说明未在服务器上启用调试 WCF 托管在IIS上 4.ChannelFact ...

  9. linux必会的60个命令

    ◆ 安装和登录命令:login.shutdown.halt.reboot.install.mount.umount.chsh.exit.last: ◆ 文件处理命令:file.mkdir.grep.d ...

  10. C# 验证码识别基础方法及源码

    先说说写这个的背景 最近有朋友在搞一个东西,已经做的挺不错了,最后想再完美一点,于是乎就提议把这种验证码给K.O.了,于是乎就K.O.了这个验证码.达到单个图片识别时间小于200ms,500个样本人工 ...