grails - 如何在grails中使用切换用户spring安全性来覆盖用户权限

标签 grails spring-security

我正在尝试在用户gsp的内部构建一些管理工具,而不构建整个管理 Controller 和页面。

我的应用程序具有用户和管理员。用户创建一个帐户,管理员可以在用户执行某些功能之前批准该帐户。管理员在批准帐户之前使用switchUser功能来查看用户的帐户。

我只想在其中一个用户帐户页面上添加一个“批准”按钮,而不是编写代码,让管理员随后不得不回头查找用户,查找他们的记录,然后更新批准的帐户。仅对具有切换用户角色的管理员可见。问题是管理员无法切换到用户的权限才能执行“批准”操作,否则用户可以激活自己的帐户。

这就是gsp的样子:

my.gsp:

<sec:ifSwitched>
    <p><g:link controller='charge' action='activateProfile'>Approve profile</g:link> - This profile will become live in the system.</p>
</sec:ifSwitched>

我在 Controller 中使用@Secured批注

什么有效,但似乎不正确:
@Secured("permitAll() and isAuthenticated()")
def activateProfile() {
   SpringSecurityUtils.isSwitchedUser() {
      //activate the profile
   }
   else {
      //not allowed unless this is a switched user
   }
}

我想工作但不存在,因为没有isSwitchedUser()注释:
@Secured("isAuthenticated() and (hasAnyRole('ROLE_ADMIN', 'ROLE_SWITCHED_USER') or isSwitchedUser())
def activateProfile() {
   //update the database and make this user's profile active
}

当然这是行不通的,因为作为切换用户,切换后的帐户没有这两个角色,因此发生页面未授权错误:
@Secured("isAuthenticated() and (hasAnyRole('ROLE_ADMIN', 'ROLE_SWITCHED_USER'))
def activateProfile() {
   SpringSecurityUtils.isSwitchedUser() {
      //activate the profile
   }
   else {
      //not allowed unless this is a switched user
   }
}

我只是坚持使用allowAll并 checkin 操作以获得许可吗?它有效且安全,但感觉不正确。

最佳答案

您可以使用以下两种方法之一来执行此操作:

自定义权限评估程序

您可以在安全注释中使用hasPermission()方法,并创建自定义PermissionEvaluator。在代码中,如下所示:

@PreAuthorize("hasPermission(#myObject, 'update')")
public void updateSomething(myObject) {
  ..
}

PermissionEvaluator实现内部,您可以为切换用户放置检查。

安全批注中的服务调用

在安全性表达式中,可以通过在bean的名称前添加@来引用这些bean。

例如:
@PreAuthorize("@mySecurityService.isSwitchedUser() or ...")
public void doSomething(myObject) {
  ..
}

更多详细信息:
两种方法都需要一些设置。不久前,我就这两种方法写了更详细的答案。您可以在这里找到它:Grails custom security evaluator

关于grails - 如何在grails中使用切换用户spring安全性来覆盖用户权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22308535/

相关文章:

grails - 具有默认参数的Groovy列表方法不匹配

spring-boot - 无法使用 KeycloakAutoConfiguration 使用 Spring Boot Security UnsatisfiedDependencyException 设置 Keycloak

spring-mvc - @WithMockUser 忽略用户名、密码字段?

spring - 有继承关系时如何过滤特定的类?

java - 处理程序之前的函数 spring 3

spring - 保持 Spring Security session 超时的区域设置

java - 在自定义 JSR-303 validator 中使用 @Autowired 组件

java - STS - 无法运行应用程序

grails - 如何获取具有指定条件的所有详细信息对象?

grails - grails分页设置页数限制