如何使用spring security插件获取当前用户角色?
我在我的 grails 应用程序中使用 spring-security-core 插件。我需要知道当前用户在控制器操作中的角色。我怎样才能找回它?
I am using the spring-security-core plugin in my grails app. I need to know the current user's role in a controller action. How can I retrieve that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以将
springSecurityService
注入控制器:def springSecurityService
,然后在您的操作中调用:
def Roles = springSecurityService.getPrincipal().getAuthorities()
请参阅此处的文档 。
You can inject
springSecurityService
into your controller:def springSecurityService
and then in your action, call:
def roles = springSecurityService.getPrincipal().getAuthorities()
See the docs here.
从控制器中,您可以使用插件添加到元类的两个方法,
getPrincipal
和isLoggedIn
:如果该操作是安全的,您可以跳过
loggedIn
/isLoggedIn()
检查。From a controller you can use two methods the plugin adds to the metaclass,
getPrincipal
andisLoggedIn
:If the action is secured you can skip the
loggedIn
/isLoggedIn()
check.如果您只需要检查用户是否处于特定角色,请使用 SpringSecurityUtils.ifAllGranted ,它接受单个字符串作为参数,其中包含以逗号分隔的角色列表。如果当前用户属于所有用户,则返回 true。 SpringSecurityUtils 还具有 ifAnyGranted、ifNotGranted 等方法,因此它应该适用于您想要完成的任何任务。
If you simply need to check to see if a user is in a specific role then use
SpringSecurityUtils.ifAllGranted
which takes a single String as an argument which contains a comma-delimited list of roles. It will return true if the current user belongs to all of them.SpringSecurityUtils
also has methods likeifAnyGranted
,ifNotGranted
, etc, so it should work for whatever it is you are trying to accomplish.来获取用户
To get the user
SecurityContextHolder 知道:
SecurityContextHolder knows that:
您还可以单独使用
getAuthenticatedUser()
。该方法会自动注入到每个控制器中,因此只能从控制器中使用。如果您想从其他地方访问当前登录的用户,则必须使用其他方法之一。You can also use
getAuthenticatedUser()
by itself. This method is automatically injected in every controller, and thus only available from controllers. You will have to use one of the other methods if you want to access the current logged in user from anywhere else.