Reputation: 3228
I'm wondering about how to filter Objects based on specific Users and how to give some User the auth to view just some objects with Spring Security. I mean, I have a Park.java object which links via Hibernate to a park table. Then I have User.java which are the classical User for Spring Security. I want to assign only some parks to each user so that each user can access and see only the Parks he has the auth to.
I was thinking of creating a ManyToMany relation between Park.java and User.java so to have the possibility to assign parks to users.
So User.java has
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name="user_parcheggio", joinColumns = {@JoinColumn(name="user_id") }, inverseJoinColumns = {
@JoinColumn(name="park_id") })
private Set<Park> parks = new HashSet<Park>();
public Set<Park> getParks() {
return parks;
}
public void setParks(Set<Park> parks){
this.parks = parks;
}
And Park.java has
@ManyToMany(cascade=CascadeType.ALL, mappedBy="park")
private Set<User> users = new HashSet<User>();
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
Once created the relations between users and parks, how can I be sure that every logged user can only see parks he has the auth to?
Upvotes: 0
Views: 214
Reputation: 2062
You have to validate if the requested Park
belongs to the user. From your controller you can check the user by so:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName(); //get logged in username
From Park
you can validate if the User
is valid and take actions upon that.
Upvotes: 1