1

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.

mrks_
  • 359
  • 4
  • 20
  • One solution might be implementing custom `BeanPropertyFilter` for `@JsonFilter` where you could implement the required logic (get roles from SecurityContext and filter properties based on that). More information on JsonFilters is [here](http://wiki.fasterxml.com/JacksonFeatureJsonFilter). I have not tried this personally, but feel free to give it a try. – Bohuslav Burghardt Jun 17 '15 at 20:34
  • This is a good idea. I'm hoping there's a slightly better way, but I'll try this if I can't find one. – mrks_ Jun 19 '15 at 18:23
  • Did you find a clean solution for this ? I'm having the same issue, can you check my newer question here please if you have found something ? http://stackoverflow.com/questions/35558218/jackson-jsonignore-fields-based-on-spring-security-roles – singe3 Feb 22 '16 at 16:35
  • @singe3 Sorry, I have not. I resorted to making unique DTOs and assembling the resource by role. – mrks_ Feb 22 '16 at 17:08

0 Answers0