学习spring-security的相关

	<beans:bean id="loggerListener"
		class="org.springframework.security.authentication.event.LoggerListener" />
	<http access-denied-page="/home.html"  auto-config="true">
		<intercept-url pattern="/style/**" filters="none" />
		<form-login login-page="/index.jsp"
			authentication-failure-url="/index.jsp?error=true"
			default-target-url="/login.action" />
		<logout logout-success-url="/quit.action" invalidate-session="true"/>
		
		<!-- 防止同一用户多次登录,使第二次登录失败  -->
		<session-management invalid-session-url="/index.jsp">
			<concurrency-control expired-url="/index.jsp" max-sessions="1" />
		</session-management>
		<!--filter-security-interceptor
			增加一个filter,这点与Acegi是不一样的,不能修改默认的filter了,这个filter位于FILTER_SECURITY_INTERCEPTOR之前
		 <custom-filter ref="loginFilter" before="FORM_LOGIN_FILTER"  />  
		-->
		
		<custom-filter before="FILTER_SECURITY_INTERCEPTOR" ref="urlSecurityFilter" />
	</http>

	<!--
		一个自定义的filter,必须包含authenticationManager,accessDecisionManager,securityMetadataSource三个属性,
		我们的所有控制将在这三个类中实现,解释详见具体配置
	-->
	<beans:bean id="urlSecurityFilter" class="com.winsen.auth.UrlSecurityInterceptorFilter">
		<!-- 用户拥有的权限 -->
		<beans:property name="authenticationManager" ref="myAuthenticationManager" />
		<!-- 用户是否拥有所请求资源的权限 -->
		<beans:property name="accessDecisionManager" ref="myAccessDecisionManager" />
		<!-- 资源与权限对应关系 -->
		<beans:property name="securityMetadataSource" ref="mySecurityMetadataSource" />
	</beans:bean>

	<!-- 认证管理器,实现用户认证的入口,主要实现UserDetailsService接口即可 -->
	<authentication-manager alias="myAuthenticationManager">
		<authentication-provider user-service-ref="myUserDetailServiceImpl" >
		   <!--
				如果用户的密码采用加密的话,可以加点“盐” <password-encoder hash="md5" />
			-->
			<password-encoder hash="plaintext" />
		</authentication-provider>
	</authentication-manager>
	
	<beans:bean id="myAccessDecisionManager" class="com.winsen.auth.AccessDecisionManagerImpl"></beans:bean>	
	<beans:bean id="mySecurityMetadataSource" class="com.winsen.auth.SecurityMetadataSourceImpl">
	</beans:bean>
	<beans:bean id="myUserDetailServiceImpl" class="com.winsen.manage.service.admin.UserDetailsServiceImpl">	
	</beans:bean>	

---------------------------------------------------------------------------------
spring security 的配置主要包括 http ,urlSecurityFilter bean, authentication-manager,myAccessDecisionManager,
myUserDetailServiceImpl,mySecurityMetadataSource几部分,其中http  定义过滤规则和提供的默认过滤的一些基础配置,包括登陆,登出,session管理等,和加载自定义的过滤器,或者替换提供的默认的过滤器。urlSecurityFilter bean是自定义的过滤器主要包括3个变量
。其中authenticationManager 主要用于加载登陆用户的相关信息。mySecurityMetadataSource主要用于查询系统的权限与角色的关系,,和和根据key 查询需要的权限集合。myAccessDecisionManager主要用于 验证用户是否具有相应权限,及其验证策略

---------------------------------------------------------------------------------
spring security 中文学习文档 ,讲的比较详细 http://www.fengfly.com/document/springsecurity3/appendix-namespace.html#nsa-session-mgmt
---------------------------------------------------------------------------------
主要类的主要代码
public class SecurityMetadataSourceImpl  implements FilterInvocationSecurityMetadataSource{
    @Transactional(readOnly = true)
    public  void loadResourceDefine() {  
        if(resourceMap == null) {  
            resourceMap = new HashMap<String, Collection<ConfigAttribute>>();  
            List<Resource> resources = this.resourcesDao.findAll();  
            for (Resource resource : resources) {  
                Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();  
                  //以权限名封装为Spring的security Object  
                ConfigAttribute configAttribute = new SecurityConfig(resource.getName());  
                configAttributes.add(configAttribute); 
                resourceMap.put(resource.getName(), configAttributes);  
            }  
        }            
    } 
  public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {  
    	 Collection<ConfigAttribute> resultRoleList=null;
        String requestUrl = ((FilterInvocation) object).getRequestUrl();  
        if(resourceMap == null) {  
            loadResourceDefine();  
        }  
        resultRoleList=resourceMap.get(requestUrl);
        if(resultRoleList==null){
           System.out.println(requestUrl+"---不需要验证");
        }else{
            System.out.println(requestUrl+"---需要验证");
        }
        return resultRoleList ;  
    } 
}

public class UrlSecurityInterceptorFilter extends AbstractSecurityInterceptor implements Filter{
 public void doFilter(ServletRequest request, ServletResponse response,  
            FilterChain chain) throws IOException, ServletException {  
        FilterInvocation fi = new FilterInvocation(request, response, chain);  
        invoke(fi);  
    }  
      
    private void invoke(FilterInvocation object) throws IOException, ServletException {  
        // object为FilterInvocation对象  org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl
    	Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 	
        //1.获取请求资源的权限  
        //执行
    	Collection<ConfigAttribute> attributes = securityMetadataSource.getAttributes(object); 
    	this.getAccessDecisionManager().decide(authentication, object, attributes); 
        InterceptorStatusToken token = super.beforeInvocation(object);     
        //2.是否拥有权限  
        try {  
        	object.getChain().doFilter(object.getRequest(), object.getResponse());  
        }catch (Exception e) {
		   	e.printStackTrace();
		} finally {  
            super.afterInvocation(token, null);  
        }  
    }  
}

public class AccessDecisionManagerImpl implements AccessDecisionManager {
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {  
        if(configAttributes == null) {    	
            return;  
        } 
       boolean result= decide(authentication, configAttributes);
       if(!result){
    	 //没有权限  
           throw new AccessDeniedException(" 没有权限访问! ");  
       }    
    }
       public boolean decide(Authentication authentication,  Collection<ConfigAttribute> configAttributes) throws InsufficientAuthenticationException {
        //所请求的资源拥有的权限(一个资源对多个权限)  
        Iterator<ConfigAttribute> iterator = configAttributes.iterator(); 
        while(iterator.hasNext()) {  
            ConfigAttribute configAttribute = iterator.next();  
            //访问所请求资源所需要的权限  
            String needPermission = configAttribute.getAttribute();  
            //用户所拥有的权限authentication  
            for(GrantedAuthority ga : authentication.getAuthorities()) {  
            	/*** 验证方式*/
                if(needPermission.equals(ga.getAuthority())) {        
                    return true;  
                }  
            }  
        }
        return false;
    }
}
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {       
       // Manager users = this.usersDao.findByName(username);  
		Manager user=findUserByName(username);
        if(user == null) {  
            throw new UsernameNotFoundException(username);  
        }  
        Set<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(user); 
        Set<GrantedAuthority> grantedAuthsChannel= obtionGrantedAuthoritiesChannels(user);
        grantedAuths.addAll(grantedAuthsChannel);
        //设置用户状态
        boolean enables = true;  
        boolean accountNonExpired = true;  
        boolean credentialsNonExpired = true;  
        boolean accountNonLocked = true;        
        User userdetail = new User(user.getUsername(), user.getPassword(), enables, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);  
        return userdetail;  
    }  
	
	public Manager findUserByName(String username){
		Manager user =usersDao.findByName(username); 
		return user;
	}
	
    //取得用户的权限  
    private Set<GrantedAuthority> obtionGrantedAuthorities(Manager user) {  
        Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();  
        List<Resource> resources = new ArrayList<Resource>();  
        Set<Role> roles = user.getRoles();     
        for(Role role : roles) {  
            Set<Resource> tempRes = role.getResources();  
            for(Resource res : tempRes) {  
                resources.add(res);  
            }  
        }  
        for(Resource res : resources) {  
            authSet.add(new GrantedAuthorityImpl(res.getName()));  
        }  
        return authSet;  
    } 

}

你可能感兴趣的:(spring,Security)