Reputation: 1290
In advance, I'm not speaking of Content Negotiation
. Let's assume I've a simple JPA entity, by the way it is convertible with a related DTO it doesn't matter.
@Entity
public class User {
...
private String email;
private String password;
...
}
I've a RESTful controller with two different routes, a secured one and a public one.
@RestController
public class UserController {
...
@GetMapping("/public")
private User publicRoute() {
return service.getLatestUser();
}
@Secured("...")
@GetMapping("/private")
private User privateRoute() {
return service.getLatestUser();
}
}
For both routes the same entity is returned, but in the first case a public representation, let's say for a user profile, without sensitive stuff like E-Mail and Password should be returned. However in the second case a private representation, let's say for the owner itself, is required.
Is there any elegant way for doing this? I tried it on JSON level with @JsonIgnore
but it doesn't worked for me. Also I tried to use Response
-Objects, but it results in a lot of boilerplate code! Any suggestions?
See Also: Recommended by Ananthapadmanabhan there already exists some questions/resources about this topic:
Upvotes: 1
Views: 458
Reputation: 83
from Question:
Tell me what do you think of this solution?
Upvotes: 0
Reputation: 6216
You could have different DTO objects being returned from the two endpoints instead of returning the same Entity class, that way you can have control over which attributes should be there in the response.
Read here about the advantages of using a DTO .
Another approach that you could make is to have custom serializers and deserializers for your endpoint. You could read here for more details. And here
Upvotes: 2
Reputation: 1
you can write you own method if your object is not final private User ignoreEmailAndPass(User user){User usr=new User();usr.setName();//send only required fields.}
Upvotes: 0