我想在我的 Controller 的方法
上应用一些Authorizations
逻辑
我有一个名为 Interview
的端点,它具有返回 Interview
对象的 findInterviewById(id)
方法。
该应用程序拥有不同的用户 [Owner、Recruiters、Candidate 和 Guest ]
每个人都可以访问 findInterviewById(id) 来读取采访对象和 createInterview(Interview) 方法来创建采访,但每个人都必须根据自己的角色以限制模式读取或写入对象
例子
- Recruiter :可以读取
findInterviewById(id)
返回的整个面试对象
- Guest:应该只读取
findInterviewById(id)
返回的采访对象中的某些字段
createInterview(Interview)
方法也是一样,Recruiter 可以触及面试的所有领域,但 Candidate 可以触及某些领域
一些解决方案说您可以复制端点,但这不是大型应用程序的最佳实践
我怎样才能实现这个特定的授权逻辑来实现这个行为
最佳答案
您可以使用 @JsonSerialize
并根据用户的权限使用 serialize(Interview interview, JsonGenerator jgen, SerializerProvider provider)
实现所需的 JSON 响应
示例
考虑负责显示用户列表的 UserDTO 类。您必须在 DTO 或域的类级别使用 @JsonSerialize(using = CustomSerializer.class)
。
DTO/模态
@JsonSerialize(using = UserDTOSerializer.class)
public class UserDTO {
private Long id;
@NotBlank
@Pattern(regexp = Constants.LOGIN_REGEX)
@Size(min = 1, max = 50)
private String login;
@Size(max = 50)
private String firstName;
@Size(max = 50)
private String lastName;
@Email
@Size(min = 5, max = 254)
private String email;
@Size(max = 256)
private String imageUrl;
private boolean activated = false;
//getter-setters and constructors
}
自定义序列化器
现在让我们通过 @Override
serialize() 方法来实现自定义序列化程序,在其中您可以从安全上下文中获取权限并自定义响应如下
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.learning.jhipster.security.AuthoritiesConstants;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class UserDTOSerializer extends StdSerializer<UserDTO> {
public UserDTOSerializer() {
this(null);
}
public UserDTOSerializer(Class<UserDTO> t) {
super(t);
}
@Override
public void serialize(UserDTO user, JsonGenerator jgen, SerializerProvider provider) throws IOException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
jgen.writeStartObject();
if(authentication.getAuthorities().toString().contains(AuthoritiesConstants.ADMIN)) {
jgen.writeNumberField("id", user.getId());
jgen.writeStringField("login", user.getLogin());
jgen.writeBooleanField("activated", user.isActivated());
jgen.writeStringField("imageUrl", user.getImageUrl());
}
jgen.writeStringField("firstName", user.getFirstName());
jgen.writeStringField("lastName", user.getLastName());
jgen.writeStringField("email", user.getEmail());
jgen.writeEndObject();
}
}
响应
以 ROLE_USER 权限登录的用户将得到以下响应
[
{
"firstName": "User",
"lastName": "User",
"email": "user@localhost"
}
]
以 ROLE_ADMIN 身份登录的用户将收到以下响应
[
{
"id": 1,
"login": "system",
"activated": true,
"imageUrl": "",
"firstName": "System",
"lastName": "System",
"email": "system@localhost"
}
]
关于java - Spring 启动 : Customize API response based on the User Roles,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62793553/