Spring security added prefix “ROLE_” to all roles name?

前端 未结 5 1535
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 12:00

I have this code in my Web Security Config:

 @Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests         


        
5条回答
  •  清歌不尽
    2020-12-01 12:47

    In Spring 4, there are two methods hasAuthority() and hasAnyAuthority() defined in org.springframework.security.access.expression.SecurityExpressionRoot class. These two methods checks only your custom role name without adding ROLE_ prefix. Definition as follows:

    public final boolean hasAuthority(String authority) {
        return hasAnyAuthority(authority);
    }
    public final boolean hasAnyAuthority(String... authorities) {
        return hasAnyAuthorityName(null, authorities);
    }
    private boolean hasAnyAuthorityName(String prefix, String... roles) {
        Set roleSet = getAuthoritySet();
    
        for (String role : roles) {
            String defaultedRole = getRoleWithDefaultPrefix(prefix, role);
            if (roleSet.contains(defaultedRole)) {
                return true;
            }
        }
    
        return false;
    }
    private static String getRoleWithDefaultPrefix(String defaultRolePrefix, String role) {
        if (role == null) {
            return role;
        }
        if (defaultRolePrefix == null || defaultRolePrefix.length() == 0) {
            return role;
        }
        if (role.startsWith(defaultRolePrefix)) {
            return role;
        }
        return defaultRolePrefix + role;
    }
    

    Example usage:

    
        
        
        
        
        
        
        
        
        
        
        
       
        
    
    

提交回复
热议问题