SpringSecurity自定义投票器

拦截URL的时候使用自定义权限判断

1:配置文件指定自定义投票器

SpringSecurity自定义投票器_第1张图片

SpringSecurity自定义投票器_第2张图片


    
        
        
        
        
        
        

        
        
        
        
            
        
    
    
    
        
          
               
               
               
        
        
    

2:自定义投票器实现类

SpringSecurity自定义投票器_第3张图片

import java.util.Collection;

import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;

import cfca.org.slf4j.Logger;
import cfca.org.slf4j.LoggerFactory;

public class GlobalAccessDecisionVoter implements AccessDecisionVoter {

    private static Logger logger = LoggerFactory.getLogger(GlobalAccessDecisionVoter.class);

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class clazz) {
        return true;
    }

    @Override
    public int vote(Authentication authentication, Object object, Collection attributes) {
        FilterInvocation fi = (FilterInvocation) object;
        String url = fi.getRequestUrl();
        logger.info("interceptor url:" + url);
        if (authentication == null) {
            return ACCESS_DENIED;
        }
        int result = ACCESS_ABSTAIN;
        Collection authorities = extractAuthorities(authentication);
        for (ConfigAttribute attribute : attributes) {
            if (attribute.getAttribute() == null) {
                continue;
            }
            if (this.supports(attribute)) {
                result = ACCESS_DENIED;
                // Attempt to find a matching granted authority
                for (GrantedAuthority authority : authorities) {
                    if (authority instanceof GlobalGrantedAuthority) {
                        GlobalGrantedAuthority globalGrantedAuthority = (GlobalGrantedAuthority) authority;
                        GlobalPermission permission = globalGrantedAuthority.getPermission();
                        if (permission != null && url.trim().equals("/"+permission.getUrl())) {
                            return ACCESS_GRANTED;
                        }
                    } else if (attribute.getAttribute().equals(authority.getAuthority())) {
                        return ACCESS_GRANTED;
                    }
                }
            }
        }

        return result;
    }

    Collection extractAuthorities(Authentication authentication) {
        return authentication.getAuthorities();
    }

}

 
  

说明

1:我目前登录用户都赋予了USER_ROLE角色,因此只要用户登录,具有USER_ROLE角色的URL都会请求通过。
2:其他的URL都拥有URL_PERMISSION角色,登录用户不具备此角色,因此只能判断用户的自定义权限是否可以匹配到。

你可能感兴趣的:(Spring全家桶)