【问题标题】:Get the authority of the user at the time of deleting it in jhipsterjhipster中删除时获取用户的权限
【发布时间】:2018-04-13 15:19:25
【问题描述】:

我需要获得我要删除的用户的权限。我的尝试如下。

@DeleteMapping("/users/{login:" + Constants.LOGIN_REGEX + "}")
@Timed
@Secured({AuthoritiesConstants.ADMIN, AuthoritiesConstants.LECTURER})
public ResponseEntity<Void> deleteUser(@PathVariable String login) {
    log.debug("REST request to delete User: {}", login);
    boolean hasAuthorityAdmin = false;
    boolean hasAuthorityMember = false;
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    hasAuthorityAdmin = authorities.contains(new SimpleGrantedAuthority(AuthoritiesConstants.ADMIN));
    hasAuthorityMember = authorities.contains(new SimpleGrantedAuthority(AuthoritiesConstants.MEMBER));
    if (hasAuthorityAdmin) {
        // delete user
        userService.deleteUser(login);
    } else {
        if (hasAuthorityMember) {
            // delete user if it is a student
            if (**x**.contains(AuthoritiesConstants.STUDENT)) {
                userService.deleteUser(login);
            }
        }
    }
    return ResponseEntity.ok().headers(HeaderUtil.createAlert("userManagement.deleted", login)).build();
}

我需要一个方法来检索它而不是 x?这意味着我需要检索要删除的权限。所以任何人都有想法。这是在 userResource.java 中。谁能帮我写代码?

假设我以会员身份登录。然后我要删除学生。所以当我点击学生记录的删除按钮时,应该可以通过一个方法得到ROLE_STUDENT。

【问题讨论】:

  • 我需要一个方法来检索它而不是 x -- 你想检索哪个?
  • 我需要获取分配给我要删除的用户的权限列表
  • 我认为你应该从数据库中提取用户角色信息。 SecurityContextHolderThreadLocal 绑定在一起,所以如果不访问数据库就无法检索。
  • 你能帮我写代码吗?我的知识较少
  • 我不了解您的数据库架构。也许,该过程可能是:从 userRole 表中按用户 ID 提取角色->检查角色是否存在->决定删除

标签: spring-boot spring-security jhipster


【解决方案1】:

应该这样做:

if (hasAuthorityMember) {
    Optional<User> user = userService.getUserWithAuthoritiesByLogin(login);
    Set<Authority> currentUserAuthorities = user.get().getAuthorities();
    for(Authority auth : currentUserAuthorities) {
        // delete user if it is a student
        if(auth.getName().equals(AuthoritiesConstants.STUDENT)) {
            userService.deleteUser(login);
        }
    }
}

使用 UserService,您可以通过登录获得用户及其权限,并且对于每个权限(如果有很多),我们检查权限的名称。如果对应Student,则删除该用户。

【讨论】:

    猜你喜欢
    • 2015-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-01
    • 1970-01-01
    • 2020-06-16
    相关资源
    最近更新 更多