2016-07-28 110 views
-1

我有域:春季安全檢查用戶有RoleGroup

用戶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 
    }  
} 
+0

你是說,如果彈簧支持角色組這是角色的列表不知道生根粉呢?。我會爲擴展角色或角色組的角色進行數據庫設計,然後在春季將它們視爲角色。 Spring支持角色列表 - > @Secured({「Admin」,「Professional」}) – surya

+0

粘貼您的用戶域類源和示例用戶類實例。 –

+0

我粘貼我的課程 –

回答

1

我想你還沒有完全掌握春季安全。

使用註釋時 - 必須在配置中啓用第一個註釋 - 默認情況下是這種情況。

然後,您可以確保選擇對整個控制器或使用這樣的事情

@Secured(['ROLE_ADMIN', 'ROLE_USER']) 

它沒有工作的所有的東西用戶具有作爲權力集團出方式的控制器操作。

雖然在你的代碼中RoleGroup類粘貼您有:

getAuthorities() 

我已經調整了我的用戶領域類,並添加以下內容:

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

所以當我有一個用戶

ie User user = User.get(1L)

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

這是一個包含所有當局

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

隨着春天的安全,你還可以用它GSPS內的列表:

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

所以回到你的問題:

您有:

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

這是你在pu到位了嗎?

從那裏:

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()