shiro demo码云地址:https://gitee.com/GntLee/GrailsShiro
GitHub地址:https://github.com/GntLee/GrailsShiro
描述:比起spring-security的权限控制,shiro的优势在于简单、通俗易懂,很容易上手。在经过多方面资料查询后,终于找到能能够用的插件。
Maven仓库一:https://dl.bintray.com/shiranr/plugins/,此仓库只有2.x的版本,2.x的版本有问题,grails3的包下面有两个domain,一个Author和Book里面都没字段,这样会导致项目无法启动
Maven仓库二:https://dl.bintray.com/animator013/plugins/,这个仓库有2.x和3.x的版本的插件包,最好用3.x的版本,我测试用的是grails-shiro:3.0.1
1、新建项目,目录结构如图
2、在build.gradle中添加maven仓库
repositories { mavenLocal() maven { url "https://repo.grails.org/grails/core" } maven { url "https://dl.bintray.com/animator013/plugins/" } }
3、引入grails-shiro插件依赖,刷新gradle
dependencies { compile 'org.grails.plugins:grails-shiro:3.0.1' }
4、通过shiro-quick-start自动创建所需的domain以及控制器
将生成的domain和controller移入自己创建的package中,默认没有package,我这里创建的package为:com.system
该命令会自动生成登录页面,如下图
5、接下来在init/BootStrap.groovy中添加初始数据便于测试,创建了两个用户,一个用户admin拥有所有权限,另一个普通用户test只能访问test控制器下面的index方法
import com.system.ShiroRole import com.system.ShiroUser import org.apache.shiro.crypto.hash.Sha256Hash class BootStrap { def init = { servletContext -> //管理员 def user1 = new ShiroUser(username: 'admin',passwordHash: new Sha256Hash("admin").toHex()).save() //普通用户 def user2 = new ShiroUser(username: 'test',passwordHash: new Sha256Hash("test").toHex()).save() def adminRole = new ShiroRole(name: "Administrator") adminRole.addToPermissions("*:*") adminRole.addToUsers(user1) adminRole.save() def user = new ShiroRole(name: "USER") user.addToPermissions("test:index") user.addToUsers(user2) user.save() } def destroy = { } }
6、创建TestController
package com.test class TestController { def index() { render "index页面" } def hello() { render "你好啊" } }
7、启动项目,进行测试
8、登录admin用户进行测试,页面用标签展示当前登录的用户:
<shiro:isLoggedIn> 当前登录用户:<shiro:principal/> </shiro:isLoggedIn>
9、我们首先访问http://localhost:8080/test/index,是可以访问的
10、访问http://localhost:8080/test/hello,是可以访问的
11、退出登录的admin账号,访问http://localhost:8080/auth/signOut
//注意默认生成的注销登录这个方法需要将注释掉webRequest.getCurrentRequest().session = null
完整方法:
def signOut() { // Log the user out of the application. SecurityUtils.subject?.logout() // webRequest.getCurrentRequest().session = null // For now, redirect back to the home page. redirect(uri: "/") }
12、登录test账号,访问http://localhost:8080/test/index,也是可以访问的
13、访问http://localhost:8080/test/hello,提示无权访问
到此,集成shiro的简单权限控制就已经完成啦!
如果标签无法访问,页面报红,可以参考https://github.com/pledbrook/grails-shiro,
将shiro3中taglib复制到你自己的项目下面就可以使用了。
https://stackoverflow.com/questions/11109714/how-do-i-get-shiros-annotations-to-work-in-grails
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!