嗨,我是 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/