I successfully created a REST web service with Jersey and provided it with java security annotations. It looks something like this.
GET /users/
GET /users/{id}
POST /users/
PUT /users/{id}
DELETE /users/{id}
I also have an area with two roles: user and admin
I defended all methods so that only admins could access them.
Now I want to give free methods PUT /users/{id}and GET /users/{id}so that users can access their own and only their resources .
Example:
GET /users/anna
GET /users/pete
Since I could not find a way to configure this through annotations, I am going to pass an HTTP request to the appropriate method to check if the user is allowed access to the resource.
This would look something like this for a method GET /users/{id}:
@GET
@Path("/users/{id}")
@RolesAllowed({"admin","user"})
@Produces(MediaType.APPLICATION_JSON)
public Response getUser(
@PathParam("id") String id,
@Context HttpServletRequest req
) {
HttpSession session = request.getSession(false);
if (session != null && session.getValue("userID").equals(id))
return getObject(User.class, id);
return Response.status(Status.UNAUTHORIZED).build();
}
aproach, , userID manualy .
, :) :
@Context
private SecurityContext security;
@GET
@Path("/users/{id}")
@RolesAllowed({"admin","user"})
@Produces(MediaType.APPLICATION_JSON)
public Response getUser(@PathParam("id") String id){
if (security.isUserInRole("user"))
if (security.getUserPrincipal().getName().equals(id))
return getObject(User.class, id);
else
return Response.status(Status.UNAUTHORIZED).build();
else
return getObject(User.class, id);
}