【问题标题】:Checking if specific user has a role检查特定用户是否具有角色
【发布时间】:2010-12-22 11:12:19
【问题描述】:

是否有一些很好的方法可以检查某些特定用户(不是登录的用户)是否具有某些特定角色?

这里是 grails 示例(普通 Java 和语法基本相同):

def user = User.get(1) //Get user with id 1
if (ifAnyGranted(user,"ROLE_ADMIN")) { //This is the line I need to implement somehow
...
}

提前致谢。

【问题讨论】:

  • 有点不清楚你在问什么。您正在寻找比上述代码“更漂亮”的东西吗?您提供的 sn-p 是否适合您?
  • 那行是一个例子,可以准确地展示我需要什么。没有函数 ifAnyGranted(user,roles)。

标签: security spring grails spring-security


【解决方案1】:

我假设,您的 User 域类拥有对您的 Role 类的 hasMany 引用,如下所示:

class User  {
    static hasMany = [authorities: Role]
    //....
}
class Role  {
    static belongsTo = User
    String description
    String authority
    //....
}

所以你的角色检查代码很简单:

User user = User.get(1)
if (user.authorities.any { it.authority == "ROLE_ADMIN" }) {
    // user is a admin
}

可以在here找到更新的答案。

【讨论】:

  • 使用此技术检查当前登录用户: def authenticateService def pricipalInfo = authenticateService.principal() def user = User.findByUsername(pricipalInfo.username) if (user.authorities.any { it .authority == "ROLE_ADMIN" }) { // 用户是管理员 }
【解决方案2】:
if (grails.plugin.springsecurity.SpringSecurityUtils.ifAllGranted("ROLE_ADMIN"))
{
   ...
}

【讨论】:

    【解决方案3】:

    如果您正在使用 Spring Security 插件并想检查当前登录的用户:

    import org.codehaus.groovy.grails.plugins.springsecurity.AuthorizeTools
    
    . . .
    
    if (AuthorizeTools.ifAllGranted("ROLE_ADMIN")){
                   //user is an admin
    }
    

    【讨论】:

    • 刚刚注意到这个问题与登录用户无关。希望这无论如何有用。
    • 我意识到这是一个旧答案,但似乎 AuthorizeTools 已被 SpringSecurityTools 取代
    【解决方案4】:

    如果你想检查当前登录的用户,你不需要查询用户域,因为你已经注入了 springSecurityService,所以你可以写:

    def springSecurityService
    
    def someAction(){
        if (principal.authorities.any { it.authority == 'ROLE_ADMIN'}){
            //...
        } else {
            //...
        }
    }
    

    【讨论】:

    • 这和Stefan的回答不一样吗?
    • @bezmax 差不多,仔细看,不需要调用 User.get(1),用 Grails 2.4.4 测试过。
    • 嗯,部分问题是if some specific user (not the one that is logged in)
    • @bezmax,好吧,我的意思是,如果有人想获得当前用户,我会编辑答案。
    猜你喜欢
    • 2019-06-16
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    相关资源
    最近更新 更多