其他分享
首页 > 其他分享> > spring-security踩坑之旅hasRole

spring-security踩坑之旅hasRole

作者:互联网

spring-boot在集成spring-security后通过@EnableGlobalMethodSecurity开启相应注解注解

在controller的具体方法上可以通过添加注解@PreAuthorize来控制权限

PreAuthorize通常使用hasRole和hasAuthority来控制访问权限,但是hasRole会有一个比较坑的地方

源码如下:

    public final boolean hasAuthority(String authority) {
        return this.hasAnyAuthority(authority);
    }

    public final boolean hasAnyAuthority(String... authorities) {
        return this.hasAnyAuthorityName((String)null, authorities);
    }

    public final boolean hasRole(String role) {
        return this.hasAnyRole(role);
    }

    public final boolean hasAnyRole(String... roles) {
        return this.hasAnyAuthorityName(this.defaultRolePrefix, roles);
    }

    private boolean hasAnyAuthorityName(String prefix, String... roles) {
        Set<String> roleSet = this.getAuthoritySet();
        String[] var4 = roles;
        int var5 = roles.length;

        for(int var6 = 0; var6 < var5; ++var6) {
            String role = var4[var6];
            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;
        } else if (defaultRolePrefix != null && defaultRolePrefix.length() != 0) {
            return role.startsWith(defaultRolePrefix) ? role : defaultRolePrefix + role;
        } else {
            return role;
        }
    }

通过源码可知hasRole在进行权限判断时会被追加前缀ROLE_
如果使用此方法判断则需要再用户权限赋值和判断处均添加ROLE_,
所以如非必须推荐hasAuthority来进行判断

private String defaultRolePrefix = "ROLE_";

标签:return,String,roles,spring,hasRole,role,defaultRolePrefix,security
来源: https://blog.csdn.net/weixin_44375512/article/details/99293832