How to get current user role with spring security

2019-02-04 06:40发布

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?

6条回答
Melony?
2楼-- · 2019-02-04 06:59

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 like ifAnyGranted, ifNotGranted, etc, so it should work for whatever it is you are trying to accomplish.

查看更多
女痞
3楼-- · 2019-02-04 06:59

To get the user

    def springSecurityService
    def principal = springSecurityService.principal
    String username = principal.username
查看更多
小情绪 Triste *
4楼-- · 2019-02-04 07:03

You can inject springSecurityService into your controller:

def springSecurityService

and then in your action, call:

def roles = springSecurityService.getPrincipal().getAuthorities()

See the docs here.

查看更多
Evening l夕情丶
5楼-- · 2019-02-04 07:09

From a controller you can use two methods the plugin adds to the metaclass, getPrincipal and isLoggedIn:

def myAction = {
   if (loggedIn) {
      // will be a List of String
      def roleNames = principal.authorities*.authority
   }
}

If the action is secured you can skip the loggedIn/isLoggedIn() check.

查看更多
淡お忘
6楼-- · 2019-02-04 07:19

SecurityContextHolder knows that:

SecurityContextHolder.getContext().getAuthentication().getAuthorities()
查看更多
祖国的老花朵
7楼-- · 2019-02-04 07:21

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.

查看更多
登录 后发表回答