`
lijingzhi
  • 浏览: 44253 次
  • 性别: Icon_minigender_1
  • 来自: 珠海
社区版块
存档分类
最新评论

20130115-使用Grails Shiro Plugin实现身份验证01

 
阅读更多

目标

  • 尽可能简单的使用Grails Shiro Plugin实现身份验证功能.

安装

  • Grails版本:2.1.1
  • 约定:在代码示例中,任何使用$开头,说明这是一个shell命令
1 $ grails create-app shiro-example
2 $ cd shiro-example
  • shiro plugin最新的插件版本是1.1.4,可以使用grails install-plugin shiro安装,但是这里使用最新的快照版本。不需要用shell安装只需要在项目的BuildConfig.groovy中增加插件的引用即可
    plugins {
        runtime ":hibernate:$grailsVersion"
        runtime ":jquery:1.8.3"
        runtime ":resources:1.1.6"
        runtime ":shiro:1.2.0-SNAPSHOT"
  • 当我们修改了BuildConfig.groovy文件后,需要对系统进行重新编译,修改才能生效
$ grails compile
  • 现在插件已经安装好了,下一步建立一个初步的脚手架,执行这个shell后,系统会帮我们生成一系列的脚手架文件,这个--prefix=[包路径]是可选项,如果使用包路径,不要忘记最后面的那个"."
$ grails shiro-quick-start --prefix=com.example.
| Created file grails-app/domain/com/example/User.groovy
| Created file grails-app/domain/com/example/Role.groovy
| Created file grails-app/realms/com/example/DbRealm.groovy
| Created file grails-app/controllers/com/example/AuthController.groovy
| Created file grails-app/views/auth/login.gsp
| Created file grails-app/conf/com/example/SecurityFilters.groovy

配置

Bootstrap.groovy

 1 import com.example.Role
 2 import com.example.User
 3 
 4 class BootStrap {
 5 
 6     def shiroSecurityService
 7 
 8     def init = { servletContext ->
 9         // Create the admin role
10         def adminRole = Role.findByName('ROLE_ADMIN') ?:
11                 new Role(name: 'ROLE_ADMIN').save(flush: true, failOnError: true)
12 
13         // Create the user role
14         def userRole = Role.findByName('ROLE_USER') ?:
15                 new Role(name: 'ROLE_USER').save(flush: true, failOnError: true)
16 
17         // Create an admin user
18         def adminUser = User.findByUsername('admin') ?:
19                 new User(username: "admin",
20                 passwordHash: shiroSecurityService.encodePassword('password'))
21                 .save(flush: true, failOnError: true)
22 
23         // Add roles to the admin user
24         assert adminUser.addToRoles(adminRole)
25         .addToRoles(userRole)
26         .save(flush: true, failOnError: true)
27 
28         // Create an standard user
29         def standardUser = User.findByUsername('joe') ?:
30                 new User(username: "joe",
31                 passwordHash: shiroSecurityService.encodePassword('password'))
32                 .save(flush: true, failOnError: true)
33 
34         // Add role to the standard user
35         assert standardUser.addToRoles(userRole)
36         .save(flush: true, failOnError: true)
37 
38     }
39     def destroy = {
40     }
41 }
  • 在代码第6行,引入了shiro的安全服务,并使用服务的encodePassword方法进行加密
  • 在代码第9到15行,新增admin和user两个角色
  • 在代码第17到21行,新增一个账号为admin的用户,并对password进行加密
  • 在代码第23到26行,给admin用户进行角色授权
  • 在代码第28到36行,给user用户进行角色授权

运行测试一下效果

$grails run-app
or
$grails -Dserver.port=8888 run-app

登录http://localhost:8080/shiro-example,点com.example.AuthController控制器,系统弹出登录窗口,输入账号和密码后,系统返回主界面,什么都没发生过。这是因为我们没有需要验证的界面,下面再增加一点东西

  • 新增一个控制器
$ grails create-controller com.example.Home
  • 给这个控制器增加三个action
 1 package com.example
 2 
 3 class HomeController {
 4 
 5     def index() {
 6         render "这个页面不需要验证"
 7     }
 8 
 9     def secured() {
10         render "这个页面需要user角色才能访问"
11     }
12 
13     def admin() {
14         render "这个页面需要admin角色才能访问"
15     }
16 }
  • 正如我们看到的,我可以分别登陆不同的视图,特定的角色才能返回正常的结果
  • 如果权限不够的用户登录到了相应页面,系统提示“You do not have permission to access this page”
  • 如果我们现在运行,并访问,不管登录到index、secured还是admin,系统都会提示“You do not have permission to access this page”

现在,分别给不同的action进行授权,打开SecurityFilters.groovy,拷贝如下代码

 1 package com.example
 2 
 3 /**
 4  * Generated by the Shiro plugin. This filters class protects all URLs
 5  * via access control by convention.
 6  */
 7 class SecurityFilters {
 8 
 9     /**
10      * Array of controller/action combinations which will be skipped from authentication
11      * if the controller and action names match. The action value can also be '*' if it
12      * encompasses all actions within the controller.
13      */
14     static nonAuthenticatedActions = [
15             [controller: 'home', action: 'index']
16     ]
17 
18     /**
19      * Array of controller/action combinations that will be authenticated against the user's
20      * role. The map also includes the roles which the controller/action pair will match
21      * against.
22      */
23     static authenticatedActions = [
24             [controller: 'home', action: 'secured', roles: ['ROLE_ADMIN', 'ROLE_USER']],
25             [controller: 'home', action: 'admin', roles: ['ROLE_ADMIN']]
26     ]
27 
28     def filters = {
29 
30         all(controller: '*', action: '*') {
31             before = {
32 
33                 // Determine if the controller/action belongs is not to be authenticated
34                 def needsAuth = !nonAuthenticatedActions.find {
35                     (it.controller == controllerName) &&
36                             ((it.action == '*') || (it.action == actionName))
37                 }
38 
39                 if (needsAuth) {
40 
41                     // Get the map within the authenticated actions which pertain to the current
42                     // controller and view.
43                     def authRoles = authenticatedActions.find {
44                         (it.controller == controllerName) &&
45                                 ((it.action == '*') || (it.action == actionName))
46                     }
47 
48                     if (authRoles) {
49 
50                         // Perform the access control for each of the roles provided in the authRoles
51                         accessControl {
52                             authRoles.roles.each { roleName ->
53                                 role(roleName)
54                             }
55                         }
56                     }
57 
58                     // Skip authentication if the authRoles was not found
59                     else {
60                         return true
61                     }
62                 }
63 
64                 // Skip authentication if no auth is needed
65                 else {
66                     return true
67                 }
68             }
69         }
70 
71     }
72 }
  • 代码第14到16行,登记不需要授权的action
  • 代码第23到26行,登记需要授权的action,并指定相应的角色

现在,大功告成,再使用不同的角色,访问不同的页面,应该可以得到不同的效果

http://localhost:8080/shiro-example/home/index : non

http://localhost:8080/shiro-example/home/secured: user,admin

http://localhost:8080/shiro-example/home/admin : admin

分享到:
评论

相关推荐

    grails-shiro-ui:Grails Shiro UI 插件

    1. 添加依赖:在Grails项目的`build.gradle`文件中添加插件依赖,如`compile 'org.grails.plugins:grails-shiro-ui:版本号'`。 2. 配置Shiro:在`Config.groovy`文件中配置Shiro的设置,包括安全 Realm、认证策略、...

    elasticsearch-grails-plugin, 恢复的ElasticSearch grails插件.zip

    elasticsearch-grails-plugin, 恢复的ElasticSearch grails插件 Elasticsearch插件插件这个项目是一个基于Elasticsearch的插件,这个项目是基于的人完成的伟大工作的。你为什么想要为原来的Elasticsearch插件提供...

    grails-datastore-gorm-plugin-support-2.0.4.RELEASE.zip

    总之,"grails-datastore-gorm-plugin-support-2.0.4.RELEASE.zip"提供了一个宝贵的资源,让开发者有机会学习和实践Grails的ORM功能和Android的MVC设计模式。无论是对Grails框架的探索,还是对Android开发的深化,这...

    Grails入门指南 -- 针对grails1.0.4更新

    ### Grails入门指南知识点 #### 一、Grails框架简介 - **背景**: Grails是一个基于Groovy语言的开源Web应用框架,适用于Java平台。它旨在简化开发过程,提高开发效率,尤其受到那些希望保留Java环境同时寻求更高效...

    grails-plugin-converters-2.3.1.zip

    Grails Plugin Converters 2.3.1 和 Box Java SDK v2 是两个在开源世界中备受关注的工具,它们各自在不同的领域提供强大的功能,而将两者结合使用,可以为开发者带来更丰富的功能和更高效的工作流程。 Grails ...

    Grails plugin: Calendar

    总的来说,"Grails plugin: Calendar"是Grails框架的一个实用扩展,它为构建时间管理功能提供了便利。通过了解和使用这个插件,开发者可以快速创建具有强大日历功能的Web应用,同时得益于Grails的灵活性和Groovy语言...

    Apache-Shiro-使用手册

    Apache-Shiro-使用手册 Apache Shiro 是一个框架,可用于身份验证和授权。本文提供了几个示例用来展示如何在 Java™ 应用程序中使用 Shiro 并给出了如何在一个 Grails web 应用程序中使用它的概述。

    grails-plugin-controllers-2.3.3.zip

    标题中的"grails-plugin-controllers-2.3.3.zip"是一个Grails插件的版本包,主要关注的是Grails框架中的控制器部分。Grails是一个基于Groovy语言的开源Web应用框架,它构建在Java平台上,旨在提高开发效率。这个插件...

    Getting-Started-with-Grails-Chinese

    5. **GSP(Grails Server Pages)和模板引擎**:描述 Grails 如何通过 GSP 实现视图层,以及模板和标签库的使用方法。 6. **Grails 插件系统**:介绍插件的安装、使用和开发,以及它们如何增强 Grails 应用的功能。...

    open-dolphin-grails-plugin:支持您将 grails 应用程序海豚化

    用于 Open Dolphin 的 Grails 插件 该插件可帮助您使用 grails 开发 Open-Dolphin 应用... grails-app/conf/BuildConfig.groovy .. . grails . project . dependency . resolution = { .. . plugins { .. . comp

    harmonyos2-grails-hibernate-search-plugin:将HibernateSearch功能集成到Grails

    Grails Hibernate 搜索插件 这个插件旨在通过几个步骤将 Hibernate Search 功能集成到 Grails 中。 入门 如果你不想从 开始,你可以开始一个新的项目: 并将以下内容添加到您的依赖项中 compile("org.grails.plugins...

    groovy-grails-tool-suite-3.6.4.RELEASE-e4.4.2-win32-x86_64.part1

    groovy-grails-tool-suite-3.6.4.RELEASE-e4.4.2-win32-x86_64.part1 共两个压缩包,解压后将扩展名.zip.bak改为.zip再次解压。

    groovy-grails-tool-suite-3.6.4.RELEASE-e4.4.2-win32-x86_64.part2

    groovy-grails-tool-suite-3.6.4.RELEASE-e4.4.2-win32-x86_64.part2 共两个包,解压后需要将扩展名.zip.bak改名为.zip重新解压。 http://dist.springsource.com/release/STS/3.8.1.RELEASE/dist/ e4.6/spring-tool-...

    grails-gradle-plugin

    classpath " org.grails:grails-gradle-plugin:2.1.2 " } } version " 0.1 " group " example " apply plugin : " grails " repositories { grails . central() // creates a maven repo for the Grails Central ...

    elasticsearch-grails-plugin-sample:grails 弹性搜索插件的示例应用程序

    如何为了充分理解用本项目实现的不同案例之间的关系,建议按以下方式使用: 通过更改Config.groovy的选项来试验不同的可用客户端模式域此应用程序中的域尝试广泛使用插件提供的映射选项。 要查找特定映射,请参阅...

    Getting-Started-with-Grails-Chinese.rar_Getting Started_grails

    本书将引导读者逐步了解Grails的基本概念和实践操作,包括环境搭建、创建第一个Grails应用、控制器和视图的使用、服务层的实现、领域模型的定义、数据库交互、GORM(Grails Object-Relational Mapping)框架的使用...

    java8-temporal-grails-plugin:Grails插件,可与Grails一起使用Java8新的Date API(Instant,LocalDate等)

    Java8 Temporal Grails插件 Java 8时态插件在Grails中集成了Java 8的新DateTime API(Instant,LocalDate,LocalTime等)。 该插件与Grails 2.5.x(支持JDK8的Grails的第一个版本)兼容。 提供将输入绑定到Java 8 ...

    Eclipse下搭建Grails项目

    - 由于Grails项目涉及GSP(Groovy Server Pages)文件,推荐使用包含JSP编辑器的Eclipse JEE版本。如果你对JSP语法熟悉且内存有限,也可选择Classic版本。 - 安装Eclipse 3.4.0 JEE版本或其他支持JSP编辑的最新...

Global site tag (gtag.js) - Google Analytics