MyAccessDecisionManager.java 2.9 KB
package com.tianbo.warehouse.security;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Iterator;

@Service
public class MyAccessDecisionManager implements AccessDecisionManager{
     /**这里没用AccessDecisionVoter访问投票管理,自定义用户的role_name与URL需要的ROLE_NAME对碰决定,参考资料:https://blog.csdn.net/kaikai8552/article/details/3965841
     * decide方法接收三个参数,decide 方法是判定是否拥有权限的决策方法
     * 其中第一个参数中保存了当前登录用户的角色信息,authentication 是释CustomUserService中循环添加到 GrantedAuthority 对象中的权限信息集合.
     * object 包含客户端发起的请求的requset信息,可转换为 HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
     * 第三个参数则是MyInvocationSecurityMetadataSourceService中的getAttributes方法传来的,表示当前请求需要的角色(可能有多个),此方法是为了判定用户请求的url 是否在权限表中,如果在权限表中,则返回给 decide 方法,用来判定用户是否有此权限。如果不在权限表中则放行。
     * @param authentication
     * @param object
     * @param configAttributes
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException{

        if(null== configAttributes || configAttributes.size() <=0) {
            return;
        }
        ConfigAttribute c;
        String needRole;
        for(Iterator<ConfigAttribute> iter = configAttributes.iterator(); iter.hasNext(); ) {
            c = iter.next();
            needRole = c.getAttribute();

            //如果URL需要的权限为匿名访问,返回
            if(("ROLE_ANONYMOUS").equals(needRole.trim())){
                return;
            }

            //authentication 为在注释1 中循环添加到 GrantedAuthority 对象中的权限信息集合
            for(GrantedAuthority ga : authentication.getAuthorities()) {
                if(needRole.trim().equals(ga.getAuthority())) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足!");
    }

    @Override
    public boolean supports(ConfigAttribute var1){

        return true;
    }

    @Override
    public boolean supports(Class<?> var1){
        return true;
    }
}