【问题标题】:Spring boot, how do I hide or prevent from loading some properties of an entitySpring boot,如何隐藏或防止加载实体的某些属性
【发布时间】: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..
}

--

【问题讨论】:

标签: java spring spring-boot spring-security


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2018-04-12
      • 2015-11-14
      • 2018-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-21
      相关资源
      最近更新 更多