【发布时间】:2011-09-21 23:16:00
【问题描述】:
我在我的 grails 应用程序中使用 spring-security-core 插件。我需要知道当前用户在控制器操作中的角色。我怎样才能找回它?
【问题讨论】:
标签: grails spring-security authorization role
我在我的 grails 应用程序中使用 spring-security-core 插件。我需要知道当前用户在控制器操作中的角色。我怎样才能找回它?
【问题讨论】:
标签: grails spring-security authorization role
您可以将springSecurityService 注入您的控制器:
def springSecurityService
然后在你的行动中,调用:
def roles = springSecurityService.getPrincipal().getAuthorities()
请参阅文档here。
【讨论】:
从控制器中,您可以使用插件添加到元类的两种方法,getPrincipal 和 isLoggedIn:
def myAction = {
if (loggedIn) {
// will be a List of String
def roleNames = principal.authorities*.authority
}
}
如果操作是安全的,您可以跳过loggedIn/isLoggedIn() 检查。
【讨论】:
springSecurityService 插件相比,在控制器中使用 authenticatedUser 是否有任何缺点?查看插件代码,它们看起来几乎相同。
如果您只需要检查用户是否属于特定角色,请使用SpringSecurityUtils.ifAllGranted,它将单个字符串作为参数,其中包含以逗号分隔的角色列表。如果当前用户属于所有用户,它将返回 true。 SpringSecurityUtils 也有 ifAnyGranted、ifNotGranted 等方法,所以它应该适用于你想要完成的任何事情。
【讨论】:
获取用户
def springSecurityService
def principal = springSecurityService.principal
String username = principal.username
【讨论】:
SecurityContextHolder 知道:
SecurityContextHolder.getContext().getAuthentication().getAuthorities()
【讨论】:
您也可以单独使用getAuthenticatedUser()。此方法会自动注入到每个控制器中,因此只能从控制器中使用。如果您想从其他任何地方访问当前登录的用户,则必须使用其他方法之一。
【讨论】: