spring-security 학습

10679 단어 springSecurity

	<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,url Security Filter bean,authentication-manager,my AccessDecisionManager,my UserDetail ServiceImpl,my Security MetadataSource 몇 부분 을 포함 하 는데 그 중에서 http  로그 인,로그 인,로그아웃,session 관리 등 과 사용자 정의 필 터 를 불 러 오 거나 기본 필 터 를 교체 하 는 기본 필터 규칙 과 기본 필 터 를 정의 합 니 다.url Security Filter bean 은 사용자 정의 필터 로 주로 세 개의 변 수 를 포함 합 니 다.그 중에서 authenticationManager 는 로그 인 사용자 의 관련 정 보 를 불 러 오 는 데 사 용 됩 니 다.my Security MetadataSource 는 주로 시스템 의 권한 과 역할 의 관 계 를 조회 하고 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;  
    } 

}

좋은 웹페이지 즐겨찾기