Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson @JsonIgnore fields based on spring security roles

In all of my Spring REST Web application, I have a lot of domain objects and DTOs.

I need to filter some domain object or DTOs fields based on the spring security roles of the user who makes the request. I want Jackson to filter the output JSON to allow/disallow specific class fields to be serialized , based on the Spring GrantedAuthorities roles of the user who tries to access the resource.

I can't create new DTO for every different view combination because it would be a mess.

I have found this solution :
Spring 3.2: Filtering Jackson JSON output based on Spring Security role
But it doesn't work, the filter is only applied once, when the first user logins. Then all the other users obtain the same filtering , no matter what their role is.

I cannot explain my problem better than Ray Holland on this blog post :
http://jackson-users.ning.com/forum/topics/jackson-custom-serialization
This is the exact same problem I'm trying to solve for a few days.

I couldn't find a clean way to do that so far.

like image 906
singe3 Avatar asked Feb 22 '16 16:02

singe3


People also ask

What is @jsonignoreproperties in Salesforce?

@JsonIgnore is used to ignore the logical property used in serialization and deserialization. @JsonIgnore can be used at setter, getter or field. @JsonIgnoreProperties ignores the specified logical properties in JSON serialization and deserialization. It is annotated at the class level.

What are @jsonignore annotations in Jackson?

This page will walk through Jackson @JsonIgnore, @JsonIgnoreProperties and @JsonIgnoreType annotations example. These annotations are used to ignore logical properties in JSON serialization and deserialization. @JsonIgnore is annotated at a class property level to ignore it.

How to tie up JSON views and spring security roles?

In order to tie up JSON views and Spring Security roles, we need to define controller advice that applies to all the controller methods in our application. And so far, the only thing we need to do is to override the beforeBodyWriteInternal method of the AbstractMappingJacksonResponseBodyAdvice class:

What is @jsonignore in JSON?

@JsonIgnore is used to ignore the logical property used in serialization and deserialization. @JsonIgnore can be used at setter, getter or field. @JsonIgnoreProperties ignores the specified logical properties in JSON serialization and deserialization.


1 Answers

It's better to use @JsonView in spring project (example)

If @JsonView isn't enough, there isn't easy solution. It is unavoidable to define specific class(interface) to implement @JsonIgnoreProperties and @JsonFilter ( take a look Jackson: Skip Objects Conditionally )

like image 156
Tody.Lu Avatar answered Nov 15 '22 06:11

Tody.Lu