java - 如何在 Spring Boot 中针对特定条件或用户角色@JsonIgnore

标签 java spring-boot spring-mvc jackson-databind

嗨,我是 Spring Boot 新手。我想实现以下逻辑,我如何实现这一点, 说我有一个模型

class Person {

    // Accessible by Level 3 or Few Roles
    private int id;
    private String name;
    private String address;

    // Accessible by Level 2 or Few Roles
    private String phoneNumber;

    //Accessible by Only Level 1 or Admin Roles 
    private String aadharNo;

    @JsonIgnore
    private LocalDateTime deletedAt;
}

级别是需要通过请求将哪些数据导出为 JSON 的说明符。并且角色的优先级很高,例如

如果访问级别 2 且角色是特权用户(现在是具有以下权限的用户),则电话号码可以以 JSON 格式导出到请求: 即使指定为级别 2,普通角色也无法访问此权限。

我怎样才能实现这一目标。有什么建议吗?

最佳答案

您可以使用@JsonView@RestControllerAdvice来做到这一点......

class View {
    public static class Level3 {} 
    public static class Level2 extends Level3 {}
    public static class Level1 extends Level2 {}
}

class Person {

    @JsonView(View.Level3.class)
    private int id;
    private String name;
    private String address;

    @JsonView(View.Level2.class)
    private String phoneNumber;

    @JsonView(View.Level1.class) 
    private String aadharNo;

    @JsonIgnore
    private LocalDateTime deletedAt;
}

并添加此配置来检查 spring-security 授权...

@RestControllerAdvice
class SecurityJsonViewControllerAdvice extends AbstractMappingJacksonResponseBodyAdvice {

    @Override
    protected void beforeBodyWriteInternal(
      MappingJacksonValue bodyContainer,
      MediaType contentType,
      MethodParameter returnType,
      ServerHttpRequest request,
      ServerHttpResponse response) {
        if (SecurityContextHolder.getContext().getAuthentication() != null
          && SecurityContextHolder.getContext().getAuthentication().getAuthorities() != null) {
            Collection<? extends GrantedAuthority> authorities
              = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
            List<Class> jsonViews = authorities.stream()
              .map(GrantedAuthority::getAuthority)
              .map(AppConfig.Role::valueOf)
              .map(View.MAPPING::get)
              .collect(Collectors.toList());
            if (jsonViews.size() == 1) {
                bodyContainer.setSerializationView(jsonViews.get(0));
                return;
            }
            throw new IllegalArgumentException("Ambiguous @JsonView declaration for roles "
              + authorities.stream()
              .map(GrantedAuthority::getAuthority).collect(Collectors.joining(",")));
        }
    }
}

关于java - 如何在 Spring Boot 中针对特定条件或用户角色@JsonIgnore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61423164/

相关文章:

spring-mvc - 添加指向 Spring Data REST Repository 资源的链接

java - 遗传算法锦标赛选择

java - 无法克隆数据

java - 单元测试 Apache-Camel JmsReplyTo 路由流程

maven - 使用 Java 11 运行 Spring Boot 应用程序时出现 java.lang.StackOverflowError

java - 带有Java注释配置的Spring MVC在资源文件夹中找不到Javascript和CSS文件

java - 改造 - 解压 gzip

java - 无法找出文件中的句子数

spring-boot - Spring 启动执行器 : have a customized status as plain text?

java - @RequestBody 没有按预期工作