Grails3.3.5集成spring security 3.2.1实现基于角色组的权限

Grails3.3.5集成spring security 3.2.1实现基于角色组的权限

1、集成spring security基于组的权限管理 
2、实现用户名、邮箱两种方式登录 
3、实现后端检验验证码功能

创建项目,build.gradle中加入依赖,通过命令创建,通过此命令会在com.system下自动建表,共7张表

compile 'org.grails.plugins:spring-security-core:3.2.0.M1'
s2-quickstart com.system User Role RequestMap --groupClassName=RoleGroup

生成如下7张表
RequestMap
Role
RoleGroup
RoleGroupRole
User
UserRole
UserRoleGroup

权限交给RequestMap表管理,添加一个权限后需要清理缓存,或者禁用缓存

方法中注入
def springSecurityService

//清理了缓存
springSecurityService.clearCachedRequestmaps()

项目用户,角色,权限初始化通过service,在BootStrap.groovy的init方法中调用服务初始化

def requestMapService

def init {

    requestMapService.init()
}

若要允许允许通过get方式注销登录,则需在application.groovy中添加

grails.plugin.springsecurity.logout.postOnly = false

页面常用标签

//未登录
<sec:ifNotLoggedIn>
    登录
</sec:ifNotLoggedIn>

//已登录
<sec:ifLoggedIn>
    <sec:username/>
</sec:ifLoggedIn>

<!--同时匹配 -->
<sec:ifAllGranted roles="ROLE_ADMIN,ROLE_USER">
    ...
</sec:ifAllGranted>

<!--匹配任意一个 -->
<sec:ifAnyGranted roles='ROLE_ADMIN,ROLE_USER'>
    ...
</sec:ifAnyGranted>

<!--匹配非ROLE_USER角色 -->
<sec:ifNotGranted roles="ROLE_USER">
    ...
</sec:ifNotGranted>

<!--获取当前登录用户 -->
<sec:loggedInUserInfo field="username"/>

<!--匹配指定角色 -->
<sec:access expression="hasRole('ROLE_USER')">
    I'm a user.
</sec:access>

<!--匹配指定请求 -->
<sec:access url="/admin/user">
    The requestURL is "/admin/user"
</sec:access>

用户名密码有两个用户1:admin admin 用户2:test test,详情查看requestMapService服务类

新增功能说明

1.新增邮箱登录支持,支持邮箱或用户名登录
2.新增登录验证码,验证码是在后端验证的,验证码通过cookie保存,所以访问只能通过127.0.0.1进行访问

效果图

132442_2ff1a9eb_493095.png

项目码云地址

  • 发表于 2018-05-28 15:54
  • 阅读 ( 1914 )
  • 分类:grails

0 条评论

请先 登录 后评论
不写代码的码农
Jonny

程序猿

65 篇文章

作家榜 »

  1. 威猛的小站长 124 文章
  2. Jonny 65 文章
  3. 江南烟雨 36 文章
  4. - Nightmare 33 文章
  5. doublechina 31 文章
  6. HJ社区-肖峰 29 文章
  7. 伪摄影 22 文章
  8. Alan 14 文章