【问题标题】:How to get current user role with spring security plugin?如何使用 Spring Security 插件获取当前用户角色?
【发布时间】:2011-09-21 23:16:00
【问题描述】:

我在我的 grails 应用程序中使用 spring-security-core 插件。我需要知道当前用户在控制器操作中的角色。我怎样才能找回它?

【问题讨论】:

    标签: grails spring-security authorization role


    【解决方案1】:

    您可以将springSecurityService 注入您的控制器:

    def springSecurityService

    然后在你的行动中,调用:

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

    请参阅文档here

    【讨论】:

    • 如果我使用以下代码,如何检查角色的值是'ROLE_USER'还是'ROLE_ADMIN'??
    • for(def role in roles){ if(role.getAuthority() == "ROLE_ADMIN") //做点什么 }
    【解决方案2】:

    从控制器中,您可以使用插件添加到元类的两种方法,getPrincipalisLoggedIn

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

    如果操作是安全的,您可以跳过loggedIn/isLoggedIn() 检查。

    【讨论】:

    • 酷,我没有意识到那些被添加到元类中。与注入 springSecurityService 插件相比,在控制器中使用 authenticatedUser 是否有任何缺点?查看插件代码,它们看起来几乎相同。
    • 没区别,只是更方便。
    • 能否将用户特定的变量(如roleNames)存储为控制器字段?我想在控制器中存储任何状态都是不安全的,因为它将被共享。我对吗?如果是这样,是否有任何技巧可以避免在控制器的所有操作中重复此代码?
    【解决方案3】:

    如果您只需要检查用户是否属于特定角色,请使用SpringSecurityUtils.ifAllGranted,它将单个字符串作为参数,其中包含以逗号分隔的角色列表。如果当前用户属于所有用户,它将返回 true。 SpringSecurityUtils 也有 ifAnyGrantedifNotGranted 等方法,所以它应该适用于你想要完成的任何事情。

    【讨论】:

      【解决方案4】:

      获取用户

          def springSecurityService
          def principal = springSecurityService.principal
          String username = principal.username
      

      【讨论】:

        【解决方案5】:

        SecurityContextHolder 知道:

        SecurityContextHolder.getContext().getAuthentication().getAuthorities()
        

        【讨论】:

          【解决方案6】:

          您也可以单独使用getAuthenticatedUser()。此方法会自动注入到每个控制器中,因此只能从控制器中使用。如果您想从其他任何地方访问当前登录的用户,则必须使用其他方法之一。

          【讨论】:

            猜你喜欢
            • 2013-02-07
            • 2012-04-22
            • 1970-01-01
            • 2020-02-12
            • 2014-03-31
            • 2014-06-10
            • 1970-01-01
            • 1970-01-01
            • 2011-10-02
            相关资源
            最近更新 更多