#Filtering Jackson JSON Output Based on Spring Security Roles and Logged in User

1 messages · Page 1 of 1 (latest)

frail arch
#

So I have a spring boot application with spring security and spring data rest, along with Postgresql as the database. I've implemented JWT authentication by following the Amigoscode video tutorial.

What I want to implement next is security-based JSON output from Jackson. For instance, take the user model. I don't want to pass certain columns, say userId, when the user requesting is an anonymous or logged-in user, but I want to send these columns when the same user asks for his own data or when an admin asks for the data.
 
I've found the solution to do something with JsonFilter and JsonView annotations, but I have no idea how to implement them.

hushed pantherBOT
#

<@&1004656351647117403> please have a look, thanks.

winter merlin
#

use DTO separate class, it's much safer

frail arch
#

Hello again Firas!

#

DTO separate class ?

rancid valve
#

data transfer object

frail arch
#

The one marked with @ Entity annotation ?

rancid valve
#

basicly a holder class to communicate between layers of your application, or a Record if your using newer java

winter merlin
#

a dto class or a record, is a class that matches few fields you want to use

rancid valve
winter merlin
#

for example the following is my userDto class

public class UserDto {
  private long id;
  private String username;
  private String address;

  // getters, setters, contructs
}
#

i build a separate class for few fields from User

#

this allows me to whatever i want with it to fulfil the request matching

#

without touching the entity class

frail arch
#

so when returning any data from entity i convert it to DTO that will filter out the not needed stuff ? sorry if i sound stupid but i have no idea tbh

winter merlin
#

if you dn't have many fields or logic

rancid valve
#

u read from your repo, that goes into an entity. When u want to communicate with a higher layer u usually use a dto or similar to communicate data. Makes it easy to change layers when needed

frail arch
#

so from database -> entity -> DTO -> Service? -> Controller?

rancid valve
#

as Fire said. If u take a user with alot sensitve data like passwords adress etc. your backend can retain that info up to a certain layer. The more public places do not need to have that data so u use a dto or record to communicate between them and loose / filter the data

rancid valve
#

something like this

frail arch
#

i see, coming from flask and express spring has a harder curve lol, thank you i will look into topic mentioned

rancid valve
#

doesnt need to be like that, but that's the flow

rancid valve
#

'saves ' time on not writing your own

frail arch
#

i will try to do this manually first, don't want to be making a black box that i dont understand the working of, then i will look into automappers thank you @rancid valve and @winter merlin

hushed pantherBOT
#

Closed the thread.