I am using Spring Security to handle the permissions of certain views with the annotation @PreAuthorize("hasRole('ROLE_ADMIN')")
. Partly this works for me because normal users can't access a certain URL for example:
http://localhost:8080/app/usuarios/detalle/1
As "ROLE_USER" I can only see up to: http://localhost:8080/app/users
As "ROLE_ADMIN" I can see up to: http://localhost:8080/app/users/detail/1
where /detalle/1
is a view that receives as a parameter the id of the selected user.
@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping(value = "/detalle/{id}")
public String detalle(@PathVariable(value = "id") int id, Map<String,Object>model, RedirectAttributes flash) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Usuario usuario_logeado = usuarioService.getUsuario(auth.getName());
Usuario usuario = usuarioService.findById(id);
if (usuario == null) {
flash.addFlashAttribute("error", "No existe el usuario");
return "redirect:/usuarios";
}
model.put("usuario_logeado", usuario_logeado.getNombre());
model.put("usuario", usuario);
return "usuarios/detalle";
}
As you will see at the beginning it brings me a table of users who are from my area and as an administrator I can go to the details of each one.
As there are several administrators and each administrator manages an area with their respective collaborators, then as an administrator I can only see certain users who are in my area, but not all of them, since by manipulating it /1
I can change the value and see the details of other users. that do not correspond to me.
How would I fix that problem, I have seen some websites where the id comes with a long character token, or maybe not.
You can create an attribute on your
Usuario
named entityadminPropietario
where you store which admin it belongs to. With a jpa query you can do something like this (Your CRUD repository or your DAO, however you work with it):In your service you implement it like this:
Then in your valid controller it is not
null
, otherwise it means that itAdmin
is trying to access ausuario
that it does not have.You
usuario_logueado
're already getting it so there's no problem with that anymore.