SpringSecurity 动态加载用户角色列表
通过实现 AccessDecisionManager 接口和 FilterInvocationSecurityMetadataSource 接口
- 实现 AccessDecisionManager 接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| @Component public class CustomAccessDecisionManager implements AccessDecisionManager { @Override public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
for(ConfigAttribute configAttribute : collection) { if("ROLE_def".equals(configAttribute.getAttribute())) { if(authentication instanceof AnonymousAuthenticationToken) { throw new AccessDeniedException("权限不足,无法访问"); } else { return; } } Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); for (GrantedAuthority authority : authorities) { if(authority.getAuthority().equals(configAttribute.getAttribute())) return; } } throw new AccessDeniedException("权限不足,无法访问"); }
@Override public boolean supports(ConfigAttribute configAttribute) { return true; }
@Override public boolean supports(Class<?> aClass) { return true; } }
|
- 实现 AccessDecisionManager 接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| @Component public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
private AntPathMatcher antPathMatcher = new AntPathMatcher();
private UserRoleService userRoleService;
@Autowired public CustomFilterInvocationSecurityMetadataSource(UserRoleService userRoleService) { this.userRoleService = userRoleService; }
@Override public Collection<ConfigAttribute> getAttributes(Object obj) throws IllegalArgumentException { String requestUrl = ((FilterInvocation) obj).getRequestUrl(); List<Role> roleList = userRoleService.getAllRole(); List<String> roles = new ArrayList<>(); for(Role role : roleList) { if(antPathMatcher.match(role.getPath(),requestUrl)) { roles.add(role.getName()); } } String[] roleStr = new String[roles.size()]; roles.toArray(roleStr); if(roles.size() != 0) return SecurityConfig.createList(roleStr); else return SecurityConfig.createList("ROLE_def"); }
@Override public Collection<ConfigAttribute> getAllConfigAttributes() { return null; }
@Override public boolean supports(Class<?> aClass) { return true; } }
|
1 2 3 4 5 6 7 8 9 10 11
| http .authorizeRequests() .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() { @Override public <O extends FilterSecurityInterceptor> O postProcess(O obj) { obj.setSecurityMetadataSource(customFilterInvocationSecurityMetadataSource); obj.setAccessDecisionManager(customAccessDecisionManager); return obj; } })
|