安装插件:install-plugin shiro

使用例子:shiro-quick-start --prefix=com.example.Shiro

这样会生成:conf/com/example/ShiroSecurityFilters.groovy和对应的ShiroRole,ShiroUser。

为方便管理,我新建了一个记录授权信息的表:AuthorizeConfig,有3个字段:

String controllerName
String actionName
static hasMany = [principalRoles: ShiroRole]


目的是能够在后台动态的修改授权。

conf/com/example/ShiroSecurityFilters.groovy的配置:

1、返回true,表示不需要授权;

2、若需要授权,在判断部分,加入:accessControl()


def filters = {
        all(controller: '*', action: '*') {
            before = {
                // 无控制器的不需要授权
                if (!controllerName) return true
                // 检查该控制器是否需要授权
                def authorizeConfig = AuthorizeConfig.findByControllerNameAndActionName(controllerName, actionName)
                if (!authorizeConfig) {
                    log.info('url[' + controllerName + '/' + actionName + ']不需要授权')
                    return true
                }
                flash.message = '未授权给当前的用户'
                // 检查是否已登陆
                if (!SecurityUtils.subject.isAuthenticated()) {
                    log.info('需要授权,但用户未登录')
                    accessControl()
                    return false
                }
                println("已登录:" + SecurityUtils.subject.principal)
                String username = SecurityUtils.subject.principal.toString()
                // 查询该用户是否有权限
                Boolean principalMe = false
                // 循环角色授权表中的权限集合
                authorizeConfig.principalRoles?.each { role ->
                    // 循环权限集合中的用户信息,若有用户属于当前权限,即表示已授权
                    role.each { user ->
                        if (user.name.equals(username))
                            principalMe = true
                    }
                }
                log.info('url[' + controllerName + '/' + actionName + ']是否授权给' + username + '?' + principalMe)
                // 若未授权,跳转到授权页面
                if (!principalMe)
                    accessControl()
            }
        }
    }


参考:

http://www.cnblogs.com/lijingzhi/archive/2013/01/15/2861002.html

http://coderberry.me/blog/2012/04/26/grails-authentication-with-shiro/