技术开发 频道

精通 Grails: 身份验证和授权

  添加角色

  为 User 分配角色是一种方便的分组方法。随后可以向组分配权限,而不是向个人分配权限。例如,现在任何人都可以创建一个新的 User。仅仅检查某个用户是否登录还远远不够。我希望限制管理员管理 User 帐户的权限。

  清单 9 向 User 添加了一个角色字段以及一条限制,限制 author 或 admin 的值:

  清单 9. 向 User 添加一个角色字段

class User {
  static constraints
= {
    login(unique:
true)
    password(password:
true)
    name()
    role(inList:[
"author", "admin"])
  }
  
  static hasMany
= [entries:Entry]
  
  
String login
  
String password
  
String name
  
String role = "author"
  
  
String toString(){
    name
  }
}

  注意,role 默认值为 author。inList 限制给出了一个复选框,只显示了两个有效选项。图 4 展示了它的实际使用:

  图 4. 将新用户角色限制为 author 或 admin  

  在 grails-app/conf/BootStrap.groovy 中创建一个 admin User,如清单 10 所示。不要忘记将 author role 添加到两个现有的 User 中。

  清单 10. 添加一个 admin User

import grails.util.GrailsUtil

class BootStrap {
  def init
= { servletContext ->
    switch(GrailsUtil.environment){
      
case "development":
        def admin
= new User(login:"admin",
                             password:
"password",
                             name:
"Administrator",
                             role:
"admin")
        admin.save()
      
        def jdoe
= new User(login:"jdoe",
                            password:
"password",
                            name:
"John Doe",
                            role:
"author")
        
//snip...
        
        def jsmith
= new User(login:"jsmith",
                            password:
"wordpass",
                            name:
"Jane Smith",
                            role:
"author")
        
//snip...
        
      break

      
case "production":
      break
    }

  }
  def destroy
= {
  }
}

  最后,添加清单 11 中的代码,将所有 User 帐户活动限制为只有拥有 admin 角色的人员才能执行:

  清单 11. 将 User 帐户管理限制为只有拥有 admin 角色的人员才能执行

class UserController {
  
  def beforeInterceptor
= [action:this.&auth,
                           except:[
"login", "authenticate", "logout"]]

  def auth() {
    
if( !(session?.user?.role == "admin") ){
      flash.message
= "You must be an administrator to perform that task."
      redirect(action:
"login")
      return
false
    }
  }
  
  
//snip...
}  

  要测试基于角色的授权,以 jsmith 身份登录并随后尝试访问 http://localhost:9090/blogito/user/create。应当被重定向到登录屏幕,如图 5 所示:

  图 5. 阻塞非管理员访问  

  现在以 admin 用户的身份登录。应当能够访问所有的闭包。

0
相关文章