0

我有这个奇怪的场景 - 我有这个PlatformUser实现Principal getName()返回它的类email。这是授权所必需的。我希望能够序列化和反序列化PlatformUser基于公共属性nameemail. 我应该如何注释我的类以使其正常工作。作为一种解决方法,我不得不将属性更改为namefullName但这违背了我的问题的目的。谢谢!

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import javax.persistence.*;
import javax.security.auth.Subject;  
import java.security.Principal;  
import java.util.*;

@Entity
public class PlatformUser implements Principal {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public int id;
    public String name;
    public String email;
    public String role = getUserRole().getRole().toString().toLowerCase();

    @Transient
    private List<GrantedAuthority> authorities;

    public PlatformUser(){}

    public PlatformUser(String email, List<GrantedAuthority> authorities) {
        this.email = email;
        this.authorities = authorities;
    }

    @Override
    public String getName() {
        return email;
    }

    @Override
    public boolean implies(Subject subject) {
        return false;
    }

    public static PlatformUser create(String email, List<GrantedAuthority> authorities) {
        if (StringUtils.isBlank(email)) throw new IllegalArgumentException("Email is blank: " + email);
        return new PlatformUser(email, authorities);
    }

    public Set<GrantedAuthority> getAuthorities() {
        UserRole role = this.getUserRole();
        Set<GrantedAuthority> authorities = new HashSet<>();
        authorities.add(new SimpleGrantedAuthority(role.getRole().authority()));
        return authorities;
    }

    public void setAuthorities(List<GrantedAuthority> authorities) {
        this.authorities = authorities;
    }

    public UserRole getUserRole() {
        return new UserRole(id, Role.ADMIN);

    }

}
4

1 回答 1

0

我在这里找到了答案:http ://www.baeldung.com/jackson-field-serializable-deserializable-or-not

我在我的配置中添加了这个@Bean以忽略 getter/setter 并仅使用属性:

@Bean
public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

    return mapper;
}
于 2017-09-25T16:50:03.963 回答