spring security入门学习(三)

动态配置权限(与二中写死相比变成了动态获取)

添加Menu.class

与Role的关系为一对多
public class Menu {
    private Integer id;
    private String pattern;
    private List roles;
}

MenuMapper接口

@Service
public interface MenuMapper {
    @Results(value = {
            @Result(property = "id",column = "id" ,id=true),
            @Result(property = "pattern",column = "pattern"),
            @Result(property = "roles",javaType = List.class,many = @Many(select = "selectRoleByMenuId"),column = "id")
    })
    @Select("select m.*,r.id as rid,r.name as rname,r.nameZh as rnameZh" +
            " from menu m left join menu_role mr on m.id=mr.mid" +
            " left join role r on mr.rid=r.id")
    List getAllMenus();

    @Select("select r.* from role r left join menu_role mr on r.id = mr.rid where mr.mid=#{menuId};")
    List selectRoleByMenuId(Integer menuId);
}
/*
getAllMenus();输出格式
[Menu {
    id = 1, pattern = '/db/**', roles = [Role {
        id = 1, name = 'ROLE_dba', nameZh = '数据库管理员'
    }]
}, Menu {
    id = 2, pattern = '/admin/**', roles = [Role {
        id = 2, name = 'ROLE_admin', nameZh = '系统管理员'
    }]
}, Menu {
    id = 3, pattern = '/user/**', roles = [Role {
        id = 3, name = 'ROLE_user', nameZh = '用户'
    }]
}]
*/

创建路径过滤器

@Component
public class MyFilter implements FilterInvocationSecurityMetadataSource {
   AntPathMatcher pathMatcher = new AntPathMatcher();
   @Autowired
   MenuService menuService;

   @Override
   public Collection getAttributes(Object object) throws IllegalArgumentException {
       String requestUrl = ((FilterInvocation) object).getRequestUrl();
       List allMenu = menuService.getAllMenu();
       for (Menu menu : allMenu) {
           if (pathMatcher.match(menu.getPattern(),requestUrl)){
               List roles = menu.getRoles();
               String[] rolesStr = new String[roles.size()];
               for (int i = 0; i < roles.size(); i++) {
                   rolesStr[i] = roles.get(i).getName();
               }
               return SecurityConfig.createList(rolesStr);
           }
       }
       return SecurityConfig.createList("ROLE_login");
   }

   @Override
   public Collection getAllConfigAttributes() {
       return null;
   }

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

@Component
public class MyAccessDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object object, Collection configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        for (ConfigAttribute configAttribute : configAttributes) {
            if ("ROLE_login".equals(configAttribute.getAttribute())){
                if (authentication instanceof AnonymousAuthenticationToken){//未登录
                    throw new AccessDeniedException("非法请求");
                }else {
                    return;
                }
            }
            Collection authorities = authentication.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                if (authority.getAuthority().equals(configAttribute.getAttribute())){//用户的权限与数据库中的匹配则放行
                    return;
                }
            }
        }
        throw new AccessDeniedException("非法请求");
    }
....
}

最后在SecurityConfig中配置FilterInvocationSecurityMetadataSource与AccessDecisionManager

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    MyFilter myFilter;
    @Autowired
    MyAccessDecisionManager myAccessDecisionManager;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .withObjectPostProcessor(new ObjectPostProcessor() {
                    @Override
                    public  O postProcess(O object) {
                        object.setAccessDecisionManager(myAccessDecisionManager);
                        object.setSecurityMetadataSource(myFilter);
                        return object;
                    }
                })
             ......
    }
}

你可能感兴趣的:(spring security入门学习(三))