How to protect REST resources so that only one role user can access it?

I successfully created a REST web service with Jersey and provided it with java security annotations. It looks something like this.

GET    /users/     // gives me all users
GET    /users/{id} // gives the user identified by {id}
POST   /users/     // creates user
PUT    /users/{id} // updates user identified by {id}
DELETE /users/{id} // delete user

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:

// user anna is logged in and uses the following methods
    GET    /users/anna // returns 200 OK
    GET    /users/pete // returns 401 UNAUTHORIZED

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);
}
+5
2

HttpServletRequest getRemoteUser() getUserPrincipal(), . , , , .

Blessed Geek REST HTTP-. REST, , , Java EE, , Java EE, .

, HTTP- . , , ( ).

.

+2

REST HTTP cookie.

REST , .

Read

GWT API Google.

GWT-Platform +

Google Federated Login, OAuth OpenID.

, OAuth 2.0.

0

All Articles