2535-springsecurity系列--關於受權角色「ROLE」前綴的問題

版本信息

<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-prefixweb

完整項目工程參考

https://github.com/starmoon1994/springsecurity-collectionspring

相關文章
相關標籤/搜索