2011-06-20 66 views
7

我有一個簡單的Grails應用程序,安裝了Spring Security Core插件,工作正常。但是,我還沒有找到任何解決方案來更新安全上下文中登錄的用戶權限。我不是在談論更新當前用戶的詳細信息(即springSecurityService.reauthenticate)。Grails Spring Security插件 - 修改已登錄的用戶權限

我的問題是:我有一個簡單的用戶管理應用程序,使用ROLE_ADMIN和ROLE_USER權限。現在,我有兩個管理員從不同的計算機同時登錄(具有ROLE_ADMIN權限),一個管理員決定將另一個管理員的權限從ROLE_ADMIN更改爲ROLE_USER。

如何更新用戶和角色,以便修改的用戶(具有新的ROLE_USER角色)不能執行任何ROLE_ADMIN級別的操作並立即重定向到ROLE_USER級別的頁面?有沒有辦法更新安全上下文,所以我不必在所有控制器操作中進行額外檢查,無論登錄用戶的權限是否已更改?我能以某種方式使用cahceUsers屬性嗎?我沒有修改cacheUser,並且我的理解是默認爲false。請糾正我,如果我錯了。

編輯: 是造成該問題的順序是

  1. 管理員 「A」 修改管理員 「B」,並設置一個新的角色(ROLE_USER)管理員 「B」

  2. 代碼調用PersonRole.removeAll(personInstanceB) and PersonRole.create(personInstanceB, roleAdmin)並且所有內容都正常更新

  3. 同時管理員「B」已在其權限被修改時登錄。管理員「B」可以繼續在ROLE_ADMIN受限制頁面上工作,直到他/她註銷並執行新的登錄。只有當時權限更新和管理員「B」具有新角色(ROLE_USER)

  4. 我希望管理員「B」被重定向到ROLE_USER頁面,當用戶更新新角色時不僅註銷後/ login

  5. 致電springSecurityService.reauthenticate personInstanceB.username)導致管理員「A」以管理員「B」身份登錄,因此這不起作用。

任何想法都會非常受歡迎。我可能錯過了一些簡單的東西,但我不知道解決方案是什麼。

乾杯, mizzzto

回答

11

這是未經測試,但給它一個嘗試

在控制器/服務類,

... 

User user = User.get(springSecurityService.principal.id) //get the user 
Role adminRole = //get or create the admin Role 
UserRole.remove user, role // remove admin Role 

Role userRole = // get or create the user Role 
UserRole.create user, role //add the user Role 

... 

if (!user.hasErrors() && user.save(flush: true)) { 
    springSecurityService.reauthenticate user.username // refresh the users security deatils 
} 

.... 

編輯

這是一個更加清晰了。

我要做的就是使用開關用戶功能。看到Switch User

  • 首先你useSwitchUserFilter屬性設置爲true
  • 你彌補這方面的特權一個新角色(例如ROLE_SWITCH_USER)這是建議。
  • 在某處你的管理頁面
  • <sec:ifAllGranted roles='ROLE_SWITCH_USER'> 
        <form action='/j_spring_security_switch_user' method='POST'> 
         Switch to user: <input type='text' name='j_username'/> <br/> 
         <input type='submit' value='Switch'/> 
        </form> 
    </sec:ifAllGranted> 
    
  • 日誌中的用戶希望使用自己的用戶名
  • 改變自己的角色設置,通過向下面的adminToUser()方法(例如)
  • 調用編輯
  • 切換回原始用戶
  • 完成。

- 您可以使用代碼的形式第一次的答案來創建你的控制器或服務的方法是採取userInstance並改變從管理員用戶thier作用。

def adminToUser(user, adminRole, userRole){ 
    UserRole.remove user, adminRole 
    UserRole.create user, userRole 
    if (!user.hasErrors() && user.save(flush: true)) { 
     springSecurityService.reauthenticate user.username 
    } 
} 
+0

您好,感謝答覆。在發佈我的問題之前,我已經按照你所描述的完成了。但是,這意味着如果您是管理員並且您更新了另一個管理員的權限 - >那麼調用springSecurityService.reauthenticate user.username將會使用修改的用戶憑證更新會話。這意味着您剛剛以您所修改的用戶「登錄」。我不希望那樣:)我會編輯我的帖子,使之更清楚我後面的內容。 – mizzzto

+0

@mizzzto看編輯! – gotomanners

+0

非常感謝,似乎現在工作得很好,很簡單,但非常強大! :)雖然,真的應該有一些更簡單的方式來通知修改後的用戶,他們的權限在用戶登錄時已被更改。我需要深入此:) – mizzzto

6

我已經兩次重新驗證解決了這個問題:

保存誰是降級的其他用戶的管理員名稱:

def originalUserName = springSecurityService.principal.name 
springSecurityService.reauthenticate user.username 
springSecurityService.reauthenticate originalUserName 
相關問題