<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.14.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> <version>1.5.14.RELEASE</version> <!--实际里面spring-security-web的版本是4.2.7--> </dependency>
// 在userdetails里给用户受权时,须要给定角色名 受权角色 List<GrantedAuthority> grantedAuthorityList = AuthorityUtils.createAuthorityList("ROLE_ADMIN","ROLE_PM","ROLE_DEV"); // 配置url受权验证相关 private void configAuthorizeRequests(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers(CustomSecurityProperties.exclusivePaths) .permitAll() .antMatchers("/admin/**", "/**/delete").hasAnyRole("ADMIN") .anyRequest() .authenticated(); }
受权的时候有ROLE前缀,可是作URL的权限配置时,并无ROLE前缀。html
版本是spring-security-core-4.2.7.RELEASE.jar
源码org.springframework.security.access.vote.RoleVoter ,类中定义了一个前缀private String rolePrefix = "ROLE_";,类中的supports方法会拿权限参数和rolePrefix进行匹配,查看是不是以ROLE_开头。java
public boolean supports(ConfigAttribute attribute) { if ((attribute.getAttribute() != null) //这里在验证前缀 && attribute.getAttribute().startsWith(getRolePrefix())) { return true; } else { return false; } } public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) { if(authentication == null) { return ACCESS_DENIED; } int result = ACCESS_ABSTAIN; Collection<? extends GrantedAuthority> authorities = extractAuthorities(authentication); for (ConfigAttribute attribute : attributes) { // 这里会遍历全部的角色值 先判断是否有前缀 有前缀的话 则进行投票 if (this.supports(attribute)) { result = ACCESS_DENIED; // Attempt to find a matching granted authority for (GrantedAuthority authority : authorities) { if (attribute.getAttribute().equals(authority.getAuthority())) { return ACCESS_GRANTED; } } } } return result; }
第77行中会验证受权角色信息是否之前缀开头git
(这是一个投票器,会对当前用户角色信息和所访问的资源信息的权限要求进行匹配,给出 -1 0 1 这样的投票值
投票器参考:https://blog.csdn.net/tjyyyangyi/article/details/79413307github
官方文档 46.3.3 What does "ROLE_" mean and why do I need it on my role names? https://docs.spring.io/spring-security/site/docs/5.0.6.RELEASE/reference/htmlsingle/#appendix-faq-role-prefix)web
https://github.com/starmoon1994/springsecurity-collectionspring