spring security入門學(xué)習(xí)(三)

動態(tài)配置權(quán)限(與二中寫死相比變成了動態(tài)獲取)

添加Menu.class

與Role的關(guān)系為一對多
public class Menu {
    private Integer id;
    private String pattern;
    private List<Role> 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<Menu> getAllMenus();

    @Select("select r.* from role r left join menu_role mr on r.id = mr.rid where mr.mid=#{menuId};")
    List<Role> selectRoleByMenuId(Integer menuId);
}
/*
getAllMenus();輸出格式
[Menu {
    id = 1, pattern = '/db/**', roles = [Role {
        id = 1, name = 'ROLE_dba', nameZh = '數(shù)據(jù)庫管理員'
    }]
}, Menu {
    id = 2, pattern = '/admin/**', roles = [Role {
        id = 2, name = 'ROLE_admin', nameZh = '系統(tǒng)管理員'
    }]
}, Menu {
    id = 3, pattern = '/user/**', roles = [Role {
        id = 3, name = 'ROLE_user', nameZh = '用戶'
    }]
}]
*/

創(chuàng)建路徑過濾器

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

   @Override
   public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
       String requestUrl = ((FilterInvocation) object).getRequestUrl();
       List<Menu> allMenu = menuService.getAllMenu();
       for (Menu menu : allMenu) {
           if (pathMatcher.match(menu.getPattern(),requestUrl)){
               List<Role> 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<ConfigAttribute> 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<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        for (ConfigAttribute configAttribute : configAttributes) {
            if ("ROLE_login".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())){//用戶的權(quán)限與數(shù)據(jù)庫中的匹配則放行
                    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<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setAccessDecisionManager(myAccessDecisionManager);
                        object.setSecurityMetadataSource(myFilter);
                        return object;
                    }
                })
             ......
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容