I have a table that is persisted as an entity. One of the columns of the table should only be serialized (via jackson) if the user has the role "ADMIN". How can I add a condition to only serialize by security role?
Code:
@Entity
@Table(name="Profile")
@SecondaryTable(name="Account", pkJoinColumns=@PrimaryKeyJoinColumn(name="id", referencedColumnName="user_id"))
public class Profile {
@Id
@GeneratedValue
@Column(name="user_id")
private Long userId;
@Column(name="username", unique=true, nullable=false)
private String username;
@Column(name="email", unique=true, nullable=false)
private String email;
@Column(table="Account", name="role", nullable=false)
@Enumerated(EnumType.STRING)
private Role role;
.....
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Role getRole() {
return role;
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void setRole(Role role) {
this.role = role;
}
The result of this would be that if a user with the appropriate security permissions (i.e., an admin) accessed http://example.com/profiles/1, then it would return the role key/value pair in the JSON, but if a non-ADMIN were to, then it would not. The @PreAuthorize annotation does not work.