Spring boot,如何隐藏或防止加载实体的某些属性

Posted

技术标签:

【中文标题】Spring boot,如何隐藏或防止加载实体的某些属性【英文标题】:Spring boot, how do I hide or prevent from loading some properties of an entity 【发布时间】:2020-07-15 10:31:24 【问题描述】:

我有一个 Account 类,其中包含用户名电子邮件和密码等所有信息。我想使用这个类来给我一些属性,比如用户名或电子邮件,以显示在他/她的个人资料页面上,但不是密码,因为我知道让这个字段通过 http/https 协议是不安全的,即使它是散列的。我试图使用@Transient 隐藏它,但是另一个类 AccountPrincipal 仍然需要这个字段来进行身份验证。什么是正确且安全的方法?

如果我尝试通过控制器获取一些帐户信息,这就是信息的样子。

[
    
        "accountId": 1,
        "userName": "pink",
        "nuggerPoint": null,
        "videos": [],
        "password": "$2a$10$jrL.YPkkvLN0fThW2e7Lne/J7ak0wb3XF4TyG.xNp9zcomuC1QHjG"
    ,
    
        "accountId": 2,
        "userName": "guy",
        "nuggerPoint": null,
        "videos": [],
        "password": "$2a$10$L2st0.RTpzeoCB72G4JG9eazZpistVxpj51UL2fVbjLxxbb6zKjaa"
    
]

--

@Entity
@Table(name = "Account")
public class Account 
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long accountId;
    private String userName;
    private String passWord;

    public Account(String username, String password, Long nuggerpoint)
        this.userName = username;
        this.passWord = password;
        this.nuggerPoint = nuggerPoint;
    
    public Long getAccountId()
        return accountId;
    
    public void setAccountId(Long accountId)
        this.accountId = accountId;
    
    public String getUserName()
        return this.userName;
    
    public void setUserName(String userName)
        this.userName = userName;
    
    public String getPassword()
        return this.passWord;
    
    public void setPassword(String password)
        this.passWord = password;
    
    // some other methods and properties

--

public class AccountPrincipal implements UserDetails 
    private Account account;
    public AccountPrincipal(Account account) 
        this.account = account;
    
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() 
        return new ArrayList<>();
    

    @Override
    public String getPassword() 
        return this.account.getPassword();
    

    @Override
    public String getUsername() 
        return this.account.getUserName();
    
    //Some other methods..

--

【问题讨论】:

您应该为此使用 DTO。 en.wikipedia.org/wiki/Data_transfer_object 【参考方案1】:

您可以在您的public String getPassword() 方法上使用@JsonIgnore 注释在序列化期间忽略该字段。

并在您的public String setPassword(String password) 上使用@JsonProperty 注释以在您想要设置时启用反序列化。

更多细节在这里:https://www.baeldung.com/jackson-field-serializable-deserializable-or-not

【讨论】:

【参考方案2】:

您可以使用所谓的 DTO 数据传输对象。这将帮助您在实体的结果与您想要向用户公开的结果之间进行映射。

【讨论】:

以上是关于Spring boot,如何隐藏或防止加载实体的某些属性的主要内容,如果未能解决你的问题,请参考以下文章

如何在Jpa中使用所选实体创建行,RestController Spring Boot

C#,Winform绑定实体框架(Entity Framework)的实体,如何去掉或隐藏导航属性?

使用 Spring Boot 和 Neo4j 通过 REST API 插入实体时出错

如何防止spring-web的spring-boot自动配置?

防止来自 Spring Boot 的数据库关闭命令

如何隐藏在后台加载的数据?