springboot+shiro整合,自定义Shiro Filter过滤器

关于springboot和shiro的整合,可以参考博文 https://blog.csdn.net/qq_41712271/article/details/105127925

假如: /admin/order= roles["admin, root"] ,表示 /admin/order 这个接口需要用户同时具备 admin 与 root 角色 才可访问,
相当于hasAllRoles() 这个判断方法


而我们的需求: 订单信息,可以由 admin 或者  root 查看, 只要用户具备其中一个角色即可

1 编写自定义过滤器类CustomRolesOrAuthorizationFilter

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.Set;

public class CustomRolesOrAuthorizationFilter extends AuthorizationFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = getSubject(request, response);

        //获取当前访问路径所需要的角色集合
        String[] rolesArray = (String[]) mappedValue;

        //没有角色限制,可以直接访问
        if (rolesArray == null || rolesArray.length == 0) {
            //no roles specified, so nothing to check - allow access.
            return true;
        }

        Set roles = CollectionUtils.asSet(rolesArray);

        //当前subject是roles 中的任意一个,则有权限访问
        for(String role : roles){
            if(subject.hasRole(role)){
                return true;
            }
        }

        return false;
    }
}

2 修改 shiro的核心类ShiroConfig

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

//自定义的过滤器导入这个包
import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){

        //没有权限,未授权就会调用此方法, 先验证登录-》再验证是否有权限
        shiroFilterFactoryBean.setUnauthorizedUrl("/pub/not_permit");

        //设置自定义filter------------- (改动1)
        Map filterMap = new LinkedHashMap<>();
        filterMap.put("roleOrFilter",new CustomRolesOrAuthorizationFilter());
        shiroFilterFactoryBean.setFilters(filterMap);

        //拦截器路径,坑一,部分路径无法进行拦截,时有时无;因为同学使用的是hashmap, 无序的,应该改为LinkedHashMap
        Map filterChainDefinitionMap = new LinkedHashMap<>();

        //-------------改动2
        filterChainDefinitionMap.put("/admin/**","roleOrFilter[admin,root]");
    }
}

 

你可能感兴趣的:(shiro,#,springboot)