`

浅谈springSecurity

阅读更多

spring security使用分类:

如何使用spring security,相信百度过的都知道,总共有四种用法,从简到深为:1、不用数据库,全部数据写在配置文件,这个也是官方文档里面的demo;2、使用数据库,根据spring security默认实现代码设计数据库,也就是说数据库已经固定了,这种方法不灵活,而且那个数据库设计得很简陋,实用性差;3、spring security和Acegi不同,它不能修改默认filter了,但支持插入filter,所以根据这个,我们可以插入自己的filter来灵活使用;4、暴力手段,修改源码,前面说的修改默认filter只是修改配置文件以替换filter而已,这种是直接改了里面的源码,但是这种不符合OO设计原则,而且不实际,不可用。

本文面向读者:

因为本文准备介绍第三种方法,所以面向的读者是已经具备了spring security基础知识的。不过不要紧,读者可以先看一下这个教程,看完应该可以使用第二种方法开发了。

spring security的简单原理:

使用众多的拦截器对url拦截,以此来管理权限。但是这么多拦截器,笔者不可能对其一一来讲,主要讲里面核心流程的两个。
首先,权限管理离不开登陆验证的,所以登陆验证拦截器AuthenticationProcessingFilter要讲;
还有就是对访问的资源管理吧,所以资源管理拦截器AbstractSecurityInterceptor要讲;
但拦截器里面的实现需要一些组件来实现,所以就有了AuthenticationManager、accessDecisionManager等组件来支撑。
    现在先大概过一遍整个流程,用户登陆,会被AuthenticationProcessingFilter拦截,调用AuthenticationManager的实现,而且AuthenticationManager会调用ProviderManager来获取用户验证信息(不同的Provider调用的服务不同,因为这些信息可以是在数据库上,可以是在LDAP服务器上,可以是xml配置文件上等),如果验证通过后会将用户的权限信息封装一个User放到spring的全局缓存SecurityContextHolder中,以备后面访问资源时使用。
访问资源(即授权管理),访问url时,会通过AbstractSecurityInterceptor拦截器拦截,其中会调用FilterInvocationSecurityMetadataSource的方法来获取被拦截url所需的全部权限,在调用授权管理器AccessDecisionManager,这个授权管理器会通过spring的全局缓存SecurityContextHolder获取用户的权限信息,还会获取被拦截的url和被拦截url所需的全部权限,然后根据所配的策略(有:一票决定,一票否定,少数服从多数等),如果权限足够,则返回,权限不够则报错并调用权限不足页面。
    虽然讲得好像好复杂,读者们可能有点晕,不过不打紧,真正通过代码的讲解在后面,读者可以看完后面的代码实现,再返回看这个简单的原理,可能会有不错的收获。
 

spring security使用实现(基于spring security3.1.4):

javaEE的入口:web.xml:
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">   
  5.      <!--加载Spring XML配置文件 -->  
  6.     <context-param>  
  7.         <param-name>contextConfigLocation</param-name>  
  8.         <param-value> classpath:securityConfig.xml           </param-value>  
  9.     </context-param>   
  10.       <!-- Spring Secutiry3.1的过滤器链配置 -->  
  11.     <filter>  
  12.         <filter-name>springSecurityFilterChain</filter-name>  
  13.         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
  14.     </filter>  
  15.     <filter-mapping>  
  16.         <filter-name>springSecurityFilterChain</filter-name>  
  17.         <url-pattern>/*</url-pattern>  
  18.     </filter-mapping>   
  19.        <!-- Spring 容器启动监听器 -->  
  20.     <listener>  
  21.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  22.     </listener>     
  23.       <!--系统欢迎页面 -->  
  24.     <welcome-file-list>  
  25.         <welcome-file>index.jsp</welcome-file>  
  26.     </welcome-file-list>  
  27. </web-app>  

上面那个配置不用多说了吧
直接上spring security的配置文件securityConfig.xml:
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <b:beans xmlns="http://www.springframework.org/schema/security"  
  3.     xmlns:b="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  6.                         http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">  
  7.   
  8.   <!--登录页面不过滤 -->  
  9.     <http pattern="/login.jsp" security="none" />  
  10.     <http access-denied-page="/accessDenied.jsp">  
  11.         <form-login login-page="/login.jsp" />  
  12.         <!--访问/admin.jsp资源的用户必须具有ROLE_ADMIN的权限 -->  
  13.         <!-- <intercept-url pattern="/admin.jsp" access="ROLE_ADMIN" /> -->  
  14.         <!--访问/**资源的用户必须具有ROLE_USER的权限 -->  
  15.         <!-- <intercept-url pattern="/**" access="ROLE_USER" /> -->  
  16.         <session-management>  
  17.             <concurrency-control max-sessions="1"  
  18.                 error-if-maximum-exceeded="false" />  
  19.         </session-management>  
  20.         <!--增加一个filter,这点与 Acegi是不一样的,不能修改默认的filter了, 这个filter位于FILTER_SECURITY_INTERCEPTOR之前 -->  
  21.         <custom-filter ref="myFilter" before="FILTER_SECURITY_INTERCEPTOR" />  
  22.     </http>  
  23.     <!--一个自定义的filter,必须包含 authenticationManager,accessDecisionManager,securityMetadataSource三个属性,   
  24.         我们的所有控制将在这三个类中实现,解释详见具体配置 -->  
  25.     <b:bean id="myFilter"  
  26.         class="com.erdangjiade.spring.security.MyFilterSecurityInterceptor">  
  27.         <b:property name="authenticationManager" ref="authenticationManager" />  
  28.         <b:property name="accessDecisionManager" ref="myAccessDecisionManagerBean" />  
  29.         <b:property name="securityMetadataSource" ref="securityMetadataSource" />  
  30.     </b:bean>  
  31.     <!--验证配置,认证管理器,实现用户认证的入口,主要实现UserDetailsService接口即可 -->  
  32.     <authentication-manager alias="authenticationManager">  
  33.         <authentication-provider user-service-ref="myUserDetailService">  
  34.             <!--如果用户的密码采用加密的话 <password-encoder hash="md5" /> -->  
  35.         </authentication-provider>  
  36.     </authentication-manager>  
  37.     <!--在这个类中,你就可以从数据库中读入用户的密码,角色信息,是否锁定,账号是否过期等 -->  
  38.     <b:bean id="myUserDetailService" class="com.erdangjiade.spring.security.MyUserDetailService" />  
  39.     <!--访问决策器,决定某个用户具有的角色,是否有足够的权限去访问某个资源 -->  
  40.     <b:bean id="myAccessDecisionManagerBean"  
  41.         class="com.erdangjiade.spring.security.MyAccessDecisionManager">  
  42.     </b:bean>  
  43.     <!--资源源数据定义,将所有的资源和权限对应关系建立起来,即定义某一资源可以被哪些角色访问 -->  
  44.     <b:bean id="securityMetadataSource"  
  45.         class="com.erdangjiade.spring.security.MyInvocationSecurityMetadataSource" />   
  46.             
  47.  </b:beans>  

其实所有配置都在<http></http>里面,首先这个版本的spring security不支持了filter=none的配置了,改成了独立的<http pattern="/login.jsp" security="none"/>,里面你可以配登陆页面、权限不足的返回页面、注销页面等,上面那些配置,我注销了一些资源和权限的对应关系,笔者这里不需要在这配死它,可以自己写拦截器来获得资源与权限的对应关系。
session-management是用来防止多个用户同时登陆一个账号的。
    最重要的是笔者自己写的拦截器myFilter(终于讲到重点了),首先这个拦截器会加载在FILTER_SECURITY_INTERCEPTOR之前(配置文件上有说),最主要的是这个拦截器里面配了三个处理类,第一个是authenticationManager,这个是处理验证的,这里需要特别说明的是:这个类不单只这个拦截器用到,还有验证拦截器AuthenticationProcessingFilter也用到 了,而且实际上的登陆验证也是AuthenticationProcessingFilter拦截器调用authenticationManager来处理的,我们这个拦截器只是为了拿到验证用户信息而已(这里不太清楚,因为authenticationManager笔者设了断点,用户登陆后再也没调用这个类了,而且调用这个类时不是笔者自己写的那个拦截器调用的,看了spring技术内幕这本书才知道是AuthenticationProcessingFilter拦截器调用的)。
securityMetadataSource这个用来加载资源与权限的全部对应关系的,并提供一个通过资源获取所有权限的方法。
accessDecisionManager这个也称为授权器,通过登录用户的权限信息、资源、获取资源所需的权限来根据不同的授权策略来判断用户是否有权限访问资源。
 
authenticationManager类可以有许多provider(提供者)提供用户验证信息,这里笔者自己写了一个类myUserDetailService来获取用户信息。
MyUserDetailService:
  1. package com.erdangjiade.spring.security;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Collection;  
  5.   
  6. import org.springframework.dao.DataAccessException;  
  7. import org.springframework.security.core.GrantedAuthority;  
  8. import org.springframework.security.core.authority.GrantedAuthorityImpl;  
  9. import org.springframework.security.core.userdetails.User;  
  10. import org.springframework.security.core.userdetails.UserDetails;  
  11. import org.springframework.security.core.userdetails.UserDetailsService;  
  12. import org.springframework.security.core.userdetails.UsernameNotFoundException;  
  13.   
  14. public class MyUserDetailService implements UserDetailsService {   
  15.       
  16.     //登陆验证时,通过username获取用户的所有权限信息,  
  17.     //并返回User放到spring的全局缓存SecurityContextHolder中,以供授权器使用  
  18.     public UserDetails loadUserByUsername(String username)   
  19.             throws UsernameNotFoundException, DataAccessException {     
  20.         Collection<GrantedAuthority> auths=new ArrayList<GrantedAuthority>();   
  21.           
  22.         GrantedAuthorityImpl auth2=new GrantedAuthorityImpl("ROLE_ADMIN");   
  23.         GrantedAuthorityImpl auth1=new GrantedAuthorityImpl("ROLE_USER");   
  24.           
  25.         if(username.equals("lcy")){   
  26.             auths=new ArrayList<GrantedAuthority>();   
  27.             auths.add(auth1);  
  28.             auths.add(auth2);        
  29.         }       
  30.           
  31.         User user = new User(username, "lcy"truetruetruetrue, auths);   
  32.         return user;    
  33.         }   
  34.     }   

其中UserDetailsService接口是spring提供的,必须实现的。别看这个类只有一个方法,而且这么简单,其中内涵玄机。
读者看到这里可能就大感疑惑了,不是说好的用数据库吗?对,但别急,等笔者慢慢给你们解析。
首先,笔者为什么不用数据库,还不是为了读者们测试方便,并简化spring security的流程,让读者抓住主线,而不是还要烦其他事(导入数据库,配置数据库,写dao等)。
这里笔者只是用几个数据模拟了从数据库中拿到的数据,也就是说ROLE_ADMIN、ROLE_USER、lcy(第一个是登陆账号)、lcy(第二个是密码)是从数据库拿出来的,这个不难实现吧,如果需要数据库时,读者可以用自己写的dao通过参数username来查询出这个用户的权限信息(或是角色信息,就是那个ROLE_*,对必须是ROLE_开头的,不然spring security不认账的,其实是spring security里面做了一个判断,必须要ROLE_开头,读者可以百度改一下),再返回spring自带的数据模型User即可。
这个写应该比较清晰、灵活吧,总之数据读者们通过什么方法获取都行,只要返回一个User对象就行了。(这也是笔者为什么要重写这个类的原因)
 
    通过MyUserDetailService拿到用户信息后,authenticationManager对比用户的密码(即验证用户),然后这个AuthenticationProcessingFilter拦截器就过咯。
 
下面要说的是另外一个拦截器,就是笔者自己写的拦截器MyFilterSecurityInterceptor:
  1. package com.erdangjiade.spring.security;  
  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. public class MyFilterSecurityInterceptor extends AbstractSecurityInterceptor  implements Filter {    
  19.       
  20.     //配置文件注入  
  21.     private FilterInvocationSecurityMetadataSource securityMetadataSource;  
  22.       
  23.     //登陆后,每次访问资源都通过这个拦截器拦截  
  24.     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {   
  25.         FilterInvocation fi = new FilterInvocation(request, response, chain);   
  26.         invoke(fi);    
  27.         }  
  28.       
  29.     public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {    
  30.         return this.securityMetadataSource;    
  31.         }     
  32.       
  33.     public Class<? extends Object> getSecureObjectClass() {   
  34.         return FilterInvocation.class;      
  35.         }    
  36.       
  37.     public void invoke(FilterInvocation fi) throws IOException, ServletException {  
  38.         //fi里面有一个被拦截的url  
  39.         //里面调用MyInvocationSecurityMetadataSource的getAttributes(Object object)这个方法获取fi对应的所有权限  
  40.         //再调用MyAccessDecisionManager的decide方法来校验用户的权限是否足够  
  41.         InterceptorStatusToken token = super.beforeInvocation(fi);  
  42.         try {  
  43.             //执行下一个拦截器  
  44.             fi.getChain().doFilter(fi.getRequest(), fi.getResponse());     
  45.             } finally {   
  46.                 super.afterInvocation(token, null);    
  47.             }     
  48.         }    
  49.     public SecurityMetadataSource obtainSecurityMetadataSource() {   
  50.         return this.securityMetadataSource;     
  51.         }   
  52.     public void setSecurityMetadataSource(  
  53.             FilterInvocationSecurityMetadataSource newSource)  
  54.     {   
  55.         this.securityMetadataSource = newSource;   
  56.     }   
  57.     public void destroy() {    
  58.           
  59.     }     
  60.     public void init(FilterConfig arg0) throws ServletException {    
  61.           
  62.     }    
  63. }  

继承AbstractSecurityInterceptor、实现Filter是必须的。
首先,登陆后,每次访问资源都会被这个拦截器拦截,会执行doFilter这个方法,这个方法调用了invoke方法,其中fi断点显示是一个url(可能重写了toString方法吧,但是里面还有一些方法的),最重要的是beforeInvocation这个方法,它首先会调用MyInvocationSecurityMetadataSource类的getAttributes方法获取被拦截url所需的权限,在调用MyAccessDecisionManager类decide方法判断用户是否够权限。弄完这一切就会执行下一个拦截器。
 
 
再看一下这个MyInvocationSecurityMetadataSource的实现:
  1. package com.erdangjiade.spring.security;  
  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.Map;  
  8.   
  9. import org.springframework.security.access.ConfigAttribute;  
  10. import org.springframework.security.access.SecurityConfig;  
  11. import org.springframework.security.web.FilterInvocation;  
  12. import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;  
  13.   
  14. import com.erdangjiade.spring.security.tool.AntUrlPathMatcher;  
  15. import com.erdangjiade.spring.security.tool.UrlMatcher;  
  16.   
  17. public class MyInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {   
  18.     private UrlMatcher urlMatcher = new AntUrlPathMatcher();   
  19.     private static Map<String, Collection<ConfigAttribute>> resourceMap = null;  
  20.       
  21.     //tomcat启动时实例化一次  
  22.     public MyInvocationSecurityMetadataSource() {  
  23.         loadResourceDefine();    
  24.         }     
  25.     //tomcat开启时加载一次,加载所有url和权限(或角色)的对应关系  
  26.     private void loadResourceDefine() {  
  27.         resourceMap = new HashMap<String, Collection<ConfigAttribute>>();   
  28.         Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();   
  29.         ConfigAttribute ca = new SecurityConfig("ROLE_USER");  
  30.         atts.add(ca);   
  31.         resourceMap.put("/index.jsp", atts);    
  32.         Collection<ConfigAttribute> attsno =new ArrayList<ConfigAttribute>();  
  33.         ConfigAttribute cano = new SecurityConfig("ROLE_NO");  
  34.         attsno.add(cano);  
  35.         resourceMap.put("/other.jsp", attsno);     
  36.         }    
  37.       
  38.     //参数是要访问的url,返回这个url对于的所有权限(或角色)  
  39.     public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {   
  40.         // 将参数转为url      
  41.         String url = ((FilterInvocation)object).getRequestUrl();     
  42.         Iterator<String>ite = resourceMap.keySet().iterator();   
  43.         while (ite.hasNext()) {           
  44.             String resURL = ite.next();    
  45.             if (urlMatcher.pathMatchesUrl(resURL, url)) {   
  46.                 return resourceMap.get(resURL);           
  47.                 }         
  48.             }   
  49.         return null;      
  50.         }    
  51.     public boolean supports(Class<?>clazz) {   
  52.             return true;    
  53.             }   
  54.     public Collection<ConfigAttribute> getAllConfigAttributes() {   
  55.         return null;    
  56.         }  
  57.     }  

实现FilterInvocationSecurityMetadataSource接口也是必须的。
首先,这里也是模拟了从数据库中获取信息。
其中loadResourceDefine方法不是必须的,这个只是加载所有的资源与权限的对应关系并缓存起来,避免每次获取权限都访问数据库(提高性能),然后getAttributes根据参数(被拦截url)返回权限集合。
这种缓存的实现其实有一个缺点,因为loadResourceDefine方法是放在构造器上调用的,而这个类的实例化只在web服务器启动时调用一次,那就是说loadResourceDefine方法只会调用一次,如果资源和权限的对应关系在启动后发生了改变,那么缓存起来的就是脏数据,而笔者这里使用的就是缓存数据,那就会授权错误了。但如果资源和权限对应关系是不会改变的,这种方法性能会好很多。
现在说回有数据库的灵活实现,读者看到这,可能会说,这还不简单,和上面MyUserDetailService类一样使用dao灵活获取数据就行啦。
如果读者这样想,那只想到了一半,想一下spring的机制(依赖注入),dao需要依赖注入吧,但这是在启动时候,那个dao可能都还没加载,所以这里需要读者自己写sessionFactory,自己写hql或sql,对,就在loadResourceDefine方法里面写(这个应该会写吧,基础来的)。那如果说想用第二种方法呢(就是允许资源和权限的对应关系改变的那个),那更加简单,根本不需要loadResourceDefine方法了,直接在getAttributes方法里面调用dao(这个是加载完,后来才会调用的,所以可以使用dao),通过被拦截url获取数据库中的所有权限,封装成Collection<ConfigAttribute>返回就行了。(灵活、简单)
注意:接口UrlMatcher和实现类AntUrlPathMatcher是笔者自己写的,这本来是spring以前版本有的,现在没有了,但是觉得好用就用会来了,直接上代码(读者也可以自己写正则表达式验证被拦截url和缓存或数据库的url是否匹配):
  1. package com.erdangjiade.spring.security.tool;  
  2.   
  3. public interface UrlMatcher{  
  4.     Object compile(String paramString);  
  5.     boolean pathMatchesUrl(Object paramObject, String paramString);  
  6.     String getUniversalMatchPattern();   
  7.     boolean requiresLowerCaseUrl();  
  8. }  

  1. package com.erdangjiade.spring.security.tool;   
  2. import org.springframework.util.AntPathMatcher;  
  3. import org.springframework.util.PathMatcher;   
  4.   
  5.   public class AntUrlPathMatcher implements UrlMatcher {    
  6.       private boolean requiresLowerCaseUrl;  
  7.       private PathMatcher pathMatcher;   
  8.       public AntUrlPathMatcher()   {   
  9.           this(true);   
  10.         
  11.   }    
  12.       public AntUrlPathMatcher(boolean requiresLowerCaseUrl)   
  13.       {    
  14.           this.requiresLowerCaseUrl = true;  
  15.       this.pathMatcher = new AntPathMatcher();   
  16.       this.requiresLowerCaseUrl = requiresLowerCaseUrl;  
  17.       }   
  18.         
  19.       public Object compile(String path) {   
  20.           if (this.requiresLowerCaseUrl) {   
  21.               return path.toLowerCase();    
  22.               }     
  23.           return path;    
  24.       }    
  25.         
  26.       public void setRequiresLowerCaseUrl(boolean requiresLowerCaseUrl){  
  27.             
  28.           this.requiresLowerCaseUrl = requiresLowerCaseUrl;   
  29.       }   
  30.         
  31.       public boolean pathMatchesUrl(Object path, String url) {   
  32.           if (("/**".equals(path)) || ("**".equals(path))) {  
  33.               return true;       
  34.               }    
  35.             
  36.           return this.pathMatcher.match((String)path, url);   
  37.       }   
  38.         
  39.       public String getUniversalMatchPattern() {  
  40.           return"/**";    
  41.       }  
  42.         
  43.       public boolean requiresLowerCaseUrl() {   
  44.           return this.requiresLowerCaseUrl;    
  45.       }    
  46.         
  47.       public String toString() {    
  48.           return super.getClass().getName() + "[requiresLowerCase='"   
  49.       + this.requiresLowerCaseUrl + "']";    
  50.       }  
  51.   }  


 
 
然后MyAccessDecisionManager类的实现:
  1. package com.erdangjiade.spring.security;  
  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.     //检查用户是否够权限访问资源  
  17.     //参数authentication是从spring的全局缓存SecurityContextHolder中拿到的,里面是用户的权限信息  
  18.     //参数object是url  
  19.     //参数configAttributes所需的权限  
  20.     public void decide(Authentication authentication, Object object,      
  21.             Collection<ConfigAttribute> configAttributes)   
  22.                     throws AccessDeniedException, InsufficientAuthenticationException {  
  23.         if(configAttributes == null){   
  24.             return;         
  25.         }    
  26.           
  27.         Iterator<ConfigAttribute> ite=configAttributes.iterator();  
  28.         while(ite.hasNext()){  
  29.             ConfigAttribute ca=ite.next();    
  30.             String needRole=((SecurityConfig)ca).getAttribute();  
  31.             for(GrantedAuthority ga : authentication.getAuthorities()){   
  32.                 if(needRole.equals(ga.getAuthority())){    
  33.                       
  34.                     return;                
  35.         }              
  36.     }        
  37. }   
  38.         //注意:执行这里,后台是会抛异常的,但是界面会跳转到所配的access-denied-page页面  
  39.         throw new AccessDeniedException("no right");     
  40. }     
  41.     public boolean supports(ConfigAttribute attribute) {   
  42.         return true;  
  43.     }    
  44.     public boolean supports(Class<?>clazz) {  
  45.         return true;   
  46.         }   
  47.     }  

接口AccessDecisionManager也是必须实现的。
decide方法里面写的就是授权策略了,笔者的实现是,没有明说需要权限的(即没有对应的权限的资源),可以访问,用户具有其中一个或多个以上的权限的可以访问。这个就看需求了,需要什么策略,读者可以自己写其中的策略逻辑。通过就返回,不通过抛异常就行了,spring security会自动跳到权限不足页面(配置文件上配的)。
 
就这样,整个流程过了一遍。
 
 

剩下的页面代码

本来想给这个demo的源码出来的,但是笔者觉得,通过这个教程一步一步读下来,并自己敲一遍代码,会比直接运行一遍demo印象更深刻,并且更容易理解里面的原理。
而且我的源码其实都公布出来了:
login.jsp:
  1. <%@page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN">  
  3. <html>  
  4. <head>  
  5. <title>登录</title>  
  6. </head>  
  7. <body>  
  8.     <form action ="j_spring_security_check" method="POST">  
  9.     <table>  
  10.         <tr>  
  11.             <td>用户:</td>  
  12.             <td><input type ='text' name='j_username'></td>  
  13.         </tr>  
  14.         <tr>  
  15.             <td>密码:</td>  
  16.             <td><input type ='password' name='j_password'></td>  
  17.         </tr>  
  18.         <tr>  
  19.             <td><input name ="reset" type="reset"></td>  
  20.             <td><input name ="submit" type="submit"></td>  
  21.         </tr>  
  22.     </table>  
  23.     </form>  
  24. </body>  
  25. </html>  

index.jsp:
  1. <%@page language="java" import="java.util.*" pageEncoding="UTF-8"%>   
  2. <%@taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>   
  3. <!DOCTYPEHTMLPUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN">  
  4.    
  5. <html>  
  6.    
  7. <head>  
  8.    
  9. <title>My JSP 'index.jsp' starting page</title>   
  10. </head>  
  11.    
  12. <body>  
  13.       <h3>这是首页</h3>欢迎  
  14.     <sec:authentication property ="name"/> !  
  15.       
  16.     <br>   
  17.     <a href="admin.jsp">进入admin页面</a>   
  18.     <a href="other.jsp">进入其它页面</a>   
  19. </body>  
  20.    
  21.   
  22. </html>  
  23.    
admin.jsp:
  1. <%@page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <!DOCTYPEHTMLPUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN">  
  3. <html>  
  4. <head>  
  5. <title>My JSP 'admin.jsp' starting page</title>  
  6. </head>  
  7. <body>  
  8.     欢迎来到管理员页面.  
  9.     <br>  
  10. </body>  
  11. </html>  

accessDenied.jsp:
  1. <%@page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <!DOCTYPEHTMLPUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN">  
  3. <html>  
  4. <head>  
  5. <title>My JSP 'admin.jsp' starting page</title>  
  6. </head>  
  7. <body>  
  8.     欢迎来到管理员页面.  
  9.     <br>  
  10. </body>  
  11. </html>  

other.jsp:
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'other.jsp' starting page</title>  
  13.       
  14.     <meta http-equiv="pragma" content="no-cache">  
  15.     <meta http-equiv="cache-control" content="no-cache">  
  16.     <meta http-equiv="expires" content="0">      
  17.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  18.     <meta http-equiv="description" content="This is my page">  
  19.     <!-- 
  20.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  21.     -->  
  22.   
  23.   </head>  
  24.     
  25.   <body>  
  26.     <h3>这里是Other页面</h3>  
  27.   </body>  
  28. </html>  
 
 
项目图:


 

最后的话:

虽然笔者没给读者们demo,但是所有源码和jar包都在这个教程里面,为什么不直接给?笔者的目的是让读者跟着教程敲一遍代码,使印象深刻(相信做这行的都知道,同样一段代码,看过和敲过的区别是多么的大),所以不惜如此来强迫大家了。
由于笔者有经常上csdn博客的习惯,所以读者有什么不懂的(或者指教的),笔者尽力解答。
 
 

补充:

第一点:

    MyUserDetailService这个类负责的是只是获取登陆用户的详细信息(包括密码、角色等),不负责和前端传过来的密码对比,只需返回User对象,后会有其他类根据User对象对比密码的正确性(框架帮我们做)。
 

第二点:

    记得MyInvocationSecurityMetadataSource这个类是负责的是获取角色与url资源的所有对应关系,并根据url查询对应的所有角色。
    今天为一个项目搭安全架构时,第一,发现上面MyInvocationSecurityMetadataSource这个类的代码有个bug
            上面的代码中,将所有的对应关系缓存到resourceMap,key是url,value是这个url对应所有角色。 
            getAttributes方法中,只要匹配到一个url就返回这个url对应所有角色,不再匹配后面的url,问题来了,当url有交集时,就有可能漏掉一些角色了:如有两个 url ,第一个是 /** ,第二个是 /role1/index.jsp ,第一个当然需要很高的权限了(因为能匹配所有 url ,即可以访问所有 url ),假设它需要的角色是 ROLE_ADMIN (不是一般人拥有的),第二个所需的角色是 ROLE_1 。    当我用 ROLE_1 这个角色访问 /role1/index.jsp 时,在getAttributes方法中,当先迭代了 /** 这个url,它就能匹配 /role1/index.jsp 这个url,并直接返回 /** 这个url对应的所有角色(在这,也就ROLE_ADMIN)给MyAccessDecisionManager这个投票类,  MyAccessDecisionManager这个类中再对比 用户的角色 ROLE_1 ,就会发现不匹配。    最后,明明可以有权访问的 url ,却不能访问了。
  
    第二,之前不是说缓存所有对应关系,需要读者自己写sessionFactory(因为在实例化这个类时,配置的sessionFactory可能还没实例化或dao还没加载好),既然这样,那笔者可以不在构造方法中加载对应关系,可以在第一次调用getAttributes方法时再加载(用静态变量缓存起来,第二次就不用再加载了,     注:其实这样不是很严谨,不过笔者这里的对应关系是不变的,单例性不需很强,更严谨的请参考笔者另一篇博文设计模式之单件模式)。
 
    修改过的MyInvocationSecurityMetadataSource类:
  1. package com.lcy.bookcrossing.springSecurity;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Collection;  
  5. import java.util.HashMap;  
  6. import java.util.HashSet;  
  7. import java.util.Iterator;  
  8. import java.util.List;  
  9. import java.util.Map;  
  10. import java.util.Set;  
  11.   
  12. import javax.annotation.Resource;  
  13.   
  14. import org.springframework.security.access.ConfigAttribute;  
  15. import org.springframework.security.access.SecurityConfig;  
  16. import org.springframework.security.web.FilterInvocation;  
  17. import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;  
  18.   
  19. import com.lcy.bookcrossing.bean.RoleUrlResource;  
  20. import com.lcy.bookcrossing.dao.IRoleUrlResourceDao;  
  21. import com.lcy.bookcrossing.springSecurity.tool.AntUrlPathMatcher;  
  22. import com.lcy.bookcrossing.springSecurity.tool.UrlMatcher;  
  23.   
  24. public class MyInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {   
  25.     private UrlMatcher urlMatcher = new AntUrlPathMatcher();   
  26. //  private static Map<String, Collection<ConfigAttribute>> resourceMap = null;  
  27.       
  28.     //将所有的角色和url的对应关系缓存起来  
  29.     private static List<RoleUrlResource> rus = null;  
  30.       
  31.     @Resource  
  32.     private IRoleUrlResourceDao roleUrlDao;  
  33.       
  34.     //tomcat启动时实例化一次  
  35.     public MyInvocationSecurityMetadataSource() {  
  36. //      loadResourceDefine();    
  37.         }     
  38.     //tomcat开启时加载一次,加载所有url和权限(或角色)的对应关系  
  39.     /*private void loadResourceDefine() { 
  40.         resourceMap = new HashMap<String, Collection<ConfigAttribute>>();  
  41.         Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();  
  42.         ConfigAttribute ca = new SecurityConfig("ROLE_USER"); 
  43.         atts.add(ca);  
  44.         resourceMap.put("/index.jsp", atts);   
  45.         Collection<ConfigAttribute> attsno =new ArrayList<ConfigAttribute>(); 
  46.         ConfigAttribute cano = new SecurityConfig("ROLE_NO"); 
  47.         attsno.add(cano); 
  48.         resourceMap.put("/other.jsp", attsno);    
  49.         }  */  
  50.       
  51.     //参数是要访问的url,返回这个url对于的所有权限(或角色)  
  52.     public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {   
  53.         // 将参数转为url      
  54.         String url = ((FilterInvocation)object).getRequestUrl();     
  55.           
  56.         //查询所有的url和角色的对应关系  
  57.         if(rus == null){  
  58.         rus = roleUrlDao.findAll();  
  59.         }  
  60.           
  61.         //匹配所有的url,并对角色去重  
  62.         Set<String> roles = new HashSet<String>();  
  63.         for(RoleUrlResource ru : rus){  
  64.             if (urlMatcher.pathMatchesUrl(ru.getUrlResource().getUrl(), url)) {   
  65.                         roles.add(ru.getRole().getRoleName());  
  66.                 }       
  67.         }  
  68.         Collection<ConfigAttribute> cas = new ArrayList<ConfigAttribute>();   
  69.         for(String role : roles){  
  70.             ConfigAttribute ca = new SecurityConfig(role);  
  71.             cas.add(ca);   
  72.         }  
  73.         return cas;  
  74.           
  75.         /*Iterator<String> ite = resourceMap.keySet().iterator();  
  76.         while (ite.hasNext()) {          
  77.             String resURL = ite.next();   
  78.             if (urlMatcher.pathMatchesUrl(resURL, url)) {  
  79.                 return resourceMap.get(resURL);          
  80.                 }        
  81.             }  
  82.         return null;    */  
  83.         }    
  84.     public boolean supports(Class<?>clazz) {   
  85.             return true;    
  86.             }   
  87.     public Collection<ConfigAttribute> getAllConfigAttributes() {   
  88.         return null;    
  89.         }  
  90.     }  

    以上代码,在getAttributes方法中缓存起所有的对应关系(可以使用依赖注入了),并匹配所有 url ,对角色进行去重(因为多个url可能有重复的角色),这样就能修复那个bug了。
 
 
 
 
 


(补充):

        这次补充不是修上面的bug,而是添加新功能
        我们知道,上面的实现的登陆界面只能传递两个参数(j_username,j_password),而且是固定的。
        总是有一个项目需求,我们的角色(ROLE_)不是很多,只需在登陆界面选择一种角色就行了,那么如何将角色类型传递到spring security呢,现在笔者对配置文件再修改修改:
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <b:beans xmlns="http://www.springframework.org/schema/security"  
  3.     xmlns:b="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  6.                         http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">  
  7.   
  8.   
  9.  <!-- 配置不需要安全管理的界面 -->  
  10.      <http pattern="/jsp/css/**" security="none"></http>  
  11.      <http pattern="/jsp/js/**" security="none"></http>  
  12.      <http pattern="/jsp/images/**" security="none"></http>  
  13.      <http pattern="/login.jsp" security="none" />  
  14.      <http pattern="/accessDenied.jsp" security="none" />  
  15.          <http pattern="/index.jsp" security="none" />  
  16.   
  17.   
  18.         <http use-expressions='true' entry-point-ref="myAuthenticationEntryPoint" access-denied-page="/accessDenied.jsp">  
  19.                   
  20.                 <!-- 使用自己自定义的登陆认证过滤器 --><!-- 这里一定要注释掉,因为我们需要重写它的过滤器 -->  
  21.                 <!-- <form-login login-page="/login.jsp"  
  22.                 authentication-failure-url="/accessDenied.jsp"      
  23.         default-target-url="/index.jsp"  
  24.                  /> -->  
  25.                 <!--访问/admin.jsp资源的用户必须具有ROLE_ADMIN的权限 -->  
  26.                 <!-- <intercept-url pattern="/admin.jsp" access="ROLE_ADMIN" /> -->  
  27.                 <!--访问/**资源的用户必须具有ROLE_USER的权限 -->  
  28.                 <!-- <intercept-url pattern="/**" access="ROLE_USER" /> -->  
  29.                 <session-management>  
  30.                         <concurrency-control max-sessions="1"  
  31.                                 error-if-maximum-exceeded="false" />  
  32.                 </session-management>  
  33.                   
  34.                 <!-- 认证和授权 --><!-- 重写登陆认证的过滤器,使我们可以拿到任何参数  -->  
  35.                 <custom-filter ref="myAuthenticationFilter" position="FORM_LOGIN_FILTER"  />  
  36.                 <custom-filter ref="myFilter" before="FILTER_SECURITY_INTERCEPTOR" />  
  37.                   
  38.                  <!-- 登出管理 -->  
  39.         <logout invalidate-session="true" logout-url="/j_spring_security_logout" />  
  40.           
  41.         </http>  
  42.           
  43.         <!-- 未登录的切入点 --><!-- 需要有个切入点 -->  
  44.     <b:bean id="myAuthenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">  
  45.         <b:property name="loginFormUrl" value="/login.jsp"></b:property>  
  46.     </b:bean>  
  47.           
  48.         <!-- 登录验证器:用户有没有登录的资格 --><!-- 这个就是重写的认证过滤器 -->  
  49.     <b:bean id="myAuthenticationFilter" class="com.lcy.springSecurity.MyAuthenticationFilter">  
  50.         <b:property name="authenticationManager" ref="authenticationManager" />  
  51.         <b:property name="filterProcessesUrl" value="/j_spring_security_check" />  
  52.         <b:property name="authenticationSuccessHandler">  
  53.             <b:bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">  
  54.                 <b:property name="defaultTargetUrl" value="/index.jsp" />  
  55.             </b:bean>  
  56.         </b:property>  
  57.         <b:property name="authenticationFailureHandler">  
  58.             <b:bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">  
  59.                 <b:property name="defaultFailureUrl" value="/accessDenied.jsp" />  
  60.             </b:bean>  
  61.         </b:property>  
  62.     </b:bean>  
  63.           
  64.           
  65.         <!--一个自定义的filter,必须包含 authenticationManager,accessDecisionManager,securityMetadataSource三个属性,我们的所有控制将在这三个类中实现,解释详见具体配置 -->  
  66.         <b:bean id="myFilter"  
  67.                 class="com.lcy.springSecurity.MyFilterSecurityInterceptor">  
  68.                 <b:property name="authenticationManager" ref="authenticationManager" />  
  69.                 <b:property name="accessDecisionManager" ref="myAccessDecisionManagerBean" />  
  70.                 <b:property name="securityMetadataSource" ref="securityMetadataSource" />  
  71.         </b:bean>  
  72.         <!--验证配置,认证管理器,实现用户认证的入口,主要实现UserDetailsService接口即可 -->  
  73.         <authentication-manager alias="authenticationManager">  
  74.                 <authentication-provider user-service-ref="myUserDetailService">  
  75.                         <!--如果用户的密码采用加密的话 <password-encoder hash="md5" /> -->  
  76.                         <!-- <password-encoder hash="md5" /> -->  
  77.                 </authentication-provider>  
  78.         </authentication-manager>  
  79.         <!--在这个类中,你就可以从数据库中读入用户的密码,角色信息,是否锁定,账号是否过期等 -->  
  80.         <b:bean id="myUserDetailService" class="com.lcy.springSecurity.MyUserDetailService" />  
  81.         <!--访问决策器,决定某个用户具有的角色,是否有足够的权限去访问某个资源 -->  
  82.         <b:bean id="myAccessDecisionManagerBean"  
  83.                 class="com.lcy.springSecurity.MyAccessDecisionManager">  
  84.         </b:bean>  
  85.         <!--资源源数据定义,将所有的资源和权限对应关系建立起来,即定义某一资源可以被哪些角色访问 -->  
  86.         <b:bean id="securityMetadataSource"  
  87.                 class="com.lcy.springSecurity.MyInvocationSecurityMetadataSource" />   
  88.             
  89.  </b:beans>  

    我现在的项目需要的是,角色只要管理员、教师、学生,所以MyAuthenticationFilter(重写的认证过滤器):
  1. package com.lcy.springSecurity;  
  2.   
  3. import javax.annotation.Resource;  
  4. import javax.servlet.http.HttpServletRequest;  
  5. import javax.servlet.http.HttpServletResponse;  
  6.   
  7. import org.springframework.security.authentication.AuthenticationServiceException;  
  8. import org.springframework.security.authentication.BadCredentialsException;  
  9. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;  
  10. import org.springframework.security.core.Authentication;  
  11. import org.springframework.security.core.AuthenticationException;  
  12. import org.springframework.security.core.context.SecurityContextHolder;  
  13. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;  
  14.   
  15. import com.lcy.dao.IAdminDao;  
  16. import com.lcy.dao.IStudentDao;  
  17. import com.lcy.dao.ITeacherDao;  
  18. import com.lcy.entity.Admin;  
  19. import com.lcy.entity.Student;  
  20. import com.lcy.entity.Teacher;  
  21.   
  22. public class MyAuthenticationFilter extends UsernamePasswordAuthenticationFilter {  
  23.           
  24.         private static final String USERNAME = "username";  
  25.         private static final String PASSWORD = "password";  
  26.   
  27.         @Resource  
  28.         private IStudentDao studentdao;  
  29.         @Resource  
  30.         private ITeacherDao teacherdao;  
  31.         @Resource  
  32.         private IAdminDao admindao;  
  33.           
  34.         @Override  
  35.         public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {  
  36.                 if (!request.getMethod().equals("POST")) {  
  37.                         throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());  
  38.                 }  
  39.   
  40.                 String username = obtainUsername(request);  
  41.                 String password = obtainPassword(request);  
  42.                 String roletype = request.getParameter("roletype");  
  43.                   
  44.                 username = username.trim();  
  45.                   
  46.                 UsernamePasswordAuthenticationToken authRequest = null;  
  47.                   
  48.                 if(!"".equals(roletype) || roletype != null){  
  49.                         if("student".equals(roletype)){  
  50.                                 Student stu = studentdao.findById(username);  
  51.                                   
  52.                                 //通过session把用户对象设置到session中  
  53.                                 request.getSession().setAttribute("session_user", stu);  
  54.                                   
  55.                                 //将角色标志在username上  
  56.                                 username = "stu"+username;  
  57.                                   
  58.                                 try {  
  59.                                         if (stu == null || !stu.getPassword().equals(password)) {  
  60.                                                 BadCredentialsException exception = new BadCredentialsException("用户名或密码不匹配");  
  61.                                                 throw exception;  
  62.                                         }  
  63.                                 } catch (Exception e) {  
  64.                                         BadCredentialsException exception = new BadCredentialsException("没有此用户");  
  65.                                         throw exception;  
  66.                                 }  
  67.                                   
  68.                                   
  69.                         }else if("teacher".equals(roletype)){  
  70.                                 Teacher tea = teacherdao.findById(username);  
  71.                                   
  72.                                 //通过session把用户对象设置到session中  
  73.                                 request.getSession().setAttribute("session_user", tea);  
  74.                                   
  75.                                 //将角色标志在username上  
  76.                                 username = "tea"+username;  
  77.                                   
  78.                                 try {  
  79.                                         if (tea == null || !tea.getPassword().equals(password)) {  
  80.                                                 BadCredentialsException exception = new BadCredentialsException("用户名或密码不匹配");  
  81.                                                 throw exception;  
  82.                                         }  
  83.                                 } catch (Exception e) {  
  84.                                         BadCredentialsException exception = new BadCredentialsException("没有此用户");  
  85.                                         throw exception;  
  86.                                 }  
  87.                                   
  88.                         }else if("admin".equals(roletype)){  
  89.                                 Admin adm = admindao.findById(username);  
  90.                                   
  91.                                 //通过session把用户对象设置到session中  
  92.                                 request.getSession().setAttribute("session_user", adm);  
  93.                                   
  94.                                 //将角色标志在username上  
  95.                                 username = "adm"+username;  
  96.                                 try {  
  97.                                         if (adm == null || !password.equals(adm.getPassword())) {  
  98.                                                 BadCredentialsException exception = new BadCredentialsException("用户名或密码不匹配");  
  99.                                                 throw exception;  
  100.                                         }  
  101.                                 } catch (Exception e) {  
  102.                                         BadCredentialsException exception = new BadCredentialsException("没有此用户");  
  103.                                         throw exception;  
  104.                                 }  
  105.                                   
  106.                         }else{  
  107.                                 BadCredentialsException exception = new BadCredentialsException("系统错误:没有对应的角色!");  
  108.                                 throw exception;  
  109.                         }  
  110.                 }  
  111.   
  112.                   
  113.                 //实现验证  
  114.                 authRequest = new UsernamePasswordAuthenticationToken(username, password);  
  115.                 //允许设置用户详细属性  
  116.                 setDetails(request, authRequest);  
  117.                 //运行  
  118.                 return this.getAuthenticationManager().authenticate(authRequest);  
  119.         }  
  120.   
  121.         @Override  
  122.         protected String obtainUsername(HttpServletRequest request) {  
  123.                 Object obj = request.getParameter(USERNAME);  
  124.                 return null == obj ? "" : obj.toString();  
  125.         }  
  126.   
  127.         @Override  
  128.         protected String obtainPassword(HttpServletRequest request) {  
  129.                 Object obj = request.getParameter(PASSWORD);  
  130.                 return null == obj ? "" : obj.toString();  
  131.         }  
  132.           
  133.         @Override  
  134.         protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {  
  135.                 super.setDetails(request, authRequest);  
  136.         }  
  137. }  

    笔者自己断点可知,执行完上面那个认证过滤器,才会执行MyUserDetailService。
        注:因为 MyUserDetailService类中的loadUserByUsername(String username) 方法只能接收一个参数username,而且这个username是从认证过滤器那里传过来的,所以笔者就通过username顺带传递角色类型过来,如上面认证过滤器,将角色类型拼在username中。到MyUserDetailService类在解开。(如有更好的方法,请评论告知,谢谢)
 
    MyUserDetailService:
  1. package com.lcy.springSecurity;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Collection;  
  5.   
  6. import javax.annotation.Resource;  
  7.   
  8. import org.springframework.dao.DataAccessException;  
  9. import org.springframework.security.core.GrantedAuthority;  
  10. import org.springframework.security.core.authority.SimpleGrantedAuthority;  
  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.   
  16. import com.lcy.dao.IAdminDao;  
  17. import com.lcy.dao.IStudentDao;  
  18. import com.lcy.dao.ITeacherDao;  
  19. import com.lcy.entity.Admin;  
  20. import com.lcy.entity.Student;  
  21. import com.lcy.entity.Teacher;  
  22.   
  23. public class MyUserDetailService implements UserDetailsService {   
  24.         @Resource  
  25.         private IStudentDao studentdao;  
  26.         @Resource  
  27.         private ITeacherDao teacherdao;  
  28.         @Resource  
  29.         private IAdminDao admindao;  
  30.           
  31.         //登陆验证时,通过username获取用户的所有权限信息,  
  32.         //并返回User放到spring的全局缓存SecurityContextHolder中,以供授权器使用  
  33.         public UserDetails loadUserByUsername(String username)   
  34.                         throws UsernameNotFoundException, DataAccessException {     
  35.                 Collection<GrantedAuthority> auths= new ArrayList<GrantedAuthority>();  
  36.                 //获取角色标志  
  37.                 String roletype = username.substring(0,3);  
  38.                 username = username.substring(3);  
  39.                 String password = "";  
  40.                   
  41.                 if("stu".equals(roletype)){  
  42.                         Student stu = studentdao.findById(username);  
  43.                         password = stu.getPassword();  
  44.                         auths.add(new SimpleGrantedAuthority("ROLE_STU"));  
  45.                 }else if("tea".equals(roletype)){  
  46.                         Teacher tea = teacherdao.findById(username);  
  47.                         password = tea.getPassword();  
  48.                         auths.add(new SimpleGrantedAuthority("ROLE_TEA"));  
  49.                 }else if("adm".equals(roletype)){  
  50.                         Admin adm = admindao.findById(username);  
  51.                         password = adm.getPassword();  
  52.                         auths.add(new SimpleGrantedAuthority("ROLE_ADM"));  
  53.                 }  
  54.                   
  55.                 User user = new User(username, password, truetruetruetrue, auths);   
  56.                 return user;    
  57.                 }   
  58.         }   
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics