I have a spring boot project with JWT being used for Spring Security. I want to implement Access Management in my project and I'm using this approach. In my project, whenever a user is created, a list of Departments is assigned to to the user. The user should be able to view and edit data that is related to the departments that have been assigned to them. I have implemented this using the below code, where the class Department
is the Master data. A list of "assigned" Departments is associated with each User.
public class User implements UserDetails {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id;
private String username;
private String password;
@JsonManagedReference
@OneToMany(cascade = CascadeType.ALL, mappedBy = "user", fetch = FetchType.EAGER)
private List<AssignedDepartment> assignedDepartmentList = new ArrayList<>();
public void setAssignedDepartment(List<AssignedDepartment> assignedDepartmentList1) {
for(AssignedDepartment assignedDepartment : assignedDepartmentList1) {
assignedDepartment.setUser(this);
this.assignedDepartmentList.add(assignedDepartment);
}
}
}
public class AssignedDepartment {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Integer id;
@JsonBackReference
@ManyToOne
@JoinColumn(name = "username", referencedColumnName = "username", nullable = false)
private User user;
@ManyToOne
@JoinColumn(name = "department_code", referencedColumnName = "departmentCode")
private Department department;
}
public class Department implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private String departmentCode;
private String departmentName;
}
Considering the above implementation and approach and the below code, where I'm getting the list of assigned Departments from the JWT token (passed as a Bearer token) that is passed in the API request, is my implementation correct and safe? The below function is called every time any API is getting hit. I have tested the code and it works fine. The list of departments is always being fetched correctly based on the JWT token that I sent in the API request. I just want to confirm if there are any issues that might arise from this approach.
private List<String> getListOfDepartmentsAssignedToCurrentUser() throws Exception {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication == null || !authentication.isAuthenticated()) {
throw new Exception("Unable to get departments for current user with authentication details: " + authentication);
}
try {
List<AssignedDepartment> userAssignedDepartments = ((User) authentication.getPrincipal()).getUserAssignedDepartments();
return userAssignedDepartments.stream()
.map(m -> m.getDepartment().getDepartmentCode())
.collect(Collectors.toList());
} catch (Exception e) {
throw new Exception("Error while streaming departments for current user with Exception: " + e.toString());
}
}