Spring Security检查User是否具有RoleGroup

时间:2016-07-28 18:34:53

标签: grails spring-security user-roles

我有域名:

用户 hasOne RoleGroup hasMany 角色

  • Exemples:

RoleGroup:管理员,专业人士,客户端......

角色: ROLE_ACTION_1,ROLE_ACTION_2,...

我如何检查用户是否有带注释@Secured的RoleGroup?

我需要检查用户是否包含RoleGroup的所有角色?

用户类:

class User implements Serializable {

    private static final long serialVersionUID = 1

    static constraints = {
        password blank: false, password: true
        username blank: false, unique: true
    }

    static mapping = {
        password column: '`password`'
        version false
        table schema: "CA"
    }

    static transients = ['springSecurityService']

    transient springSecurityService

    transient boolean enabled = true
    transient boolean accountExpired
    transient boolean accountLocked
    transient boolean passwordExpired

    String username
    String password
    RoleGroup profile

    Set<RoleGroup> getAuthorities() {
        [profile]
    }
}

RoleGroup类:

class RoleGroup implements Serializable {

    private static final long serialVersionUID = 1

    String name    

    Set<Role> getAuthorities() {
        RoleGroupRole.findAllByRoleGroup (this)*.role
    }    
}

1 个答案:

答案 0 :(得分:1)

我认为你还没有完全掌握弹簧的安全性。

使用注释时 - 必须在配置中启用第一个注释 - 默认情况下就是这种情况。

然后使用类似

之类的东西保护整个控制器或控制器操作
@Secured(['ROLE_ADMIN', 'ROLE_USER'])

它无法计算出用户拥有的所有权限组。

虽然在您在RoleGroup类中粘贴的代码中,您有:

getAuthorities()

我调整了我的用户域类并添加了以下内容:

   Set<RoleGroup> getAuthorities() {
        UserRoleGroup.findAllByUser(this)*.roleGroup
    }
    Set<RoleGroup> getAuthoritiesNames() {
        UserRoleGroup.findAllByUser(this)*.roleGroup?.name
    }

所以我有一个用户

即。用户user = User.get(1L)

def authorities = user.getAuthorities()
println "user ${user} has ${authorities}"

这是一个包含所有权限的列表

if (authorities.contains('ROLE_USER'))  {
println "WOOHOO"
}

使用spring security,您也可以在gsps中使用它:

  <sec:ifAllGranted roles="ROLE_ADMIN">
show something
</sec:ifAllGranted>

回到你的问题:

你有:

Set<RoleGroup> getAuthorities() {
        [profile]
    }

你有什么东西到位吗?

从哪里来:

class RoleGroup implements Serializable {

    private static final long serialVersionUID = 1

    String name    

    Set<Role> getAuthorities() {
        RoleGroupRole.findAllByRoleGroup (this)*.role
    }    
}

这应列出所有权限

User user = User.get(1L)
def authorities = user?.profile?.getAuthorities()
相关问题