Tom O'Brien
Tom O'Brien

Reputation: 1831

REST Design of User-based access using Jersey

So I am trying to get my head around how to design my REST resources and how security fits into all of this. I am new to REST and user authentication in general so please bear with me - I am sure this is a really stupid question.

Now I know that you can define security roles for users, and restrict access to resources depending on whether they are an admin or not.

Where I am getting confused is say I have a situation where a certain user, 1234 say, has a list of subscriptions. Now only user 1234 should be able to access his subscriptions.

GET /user_id/1234/subscriptions

In this scenario, using roles doesn't make any sense, as you would have to define roles for each user. Do we have to control this access by doing some kind of check in the code to make sure this user has access? For example:

@Path("/user_id/{user_id}/subscriptions")
@GET
public getSubscriptions(@PathParam("user_id" int user_id))
{
    if(user_id == "some code here that checks what the user_id of the current user is")
    {
        return Response.ok(getUserSubscriptionsFromDB(user_id));
    }
    else
    {
        return Response.status(Status.UNAUTHORIZED).build();
    }
}

Is this how it is supposed to be done, or have i got it all wrong? If that is how you would go about it, what would the actual code in the "" look like? What object would I be interrogating to get my hands on the user_id? [The plan is in the future to use OAUTH2 social login for google, facebook etc.... but I might just use basic authentication too]

Upvotes: 0

Views: 594

Answers (1)

Alexander B
Alexander B

Reputation: 1033

You basically got it right. The terminology for this type of authorization is Permission/Activity Based Authorization and is widely used for CRUD operations on recources like RESTful services.

A pseudo code would more look like this:

@Path("/users/{userId}/subscriptions")
@GET
public getSubscriptions(@PathParam("userId" int userId))
{
    if(getSubject().isPermitted("subscriptions:read:"+userId)
    {
        return Response.ok(getUserSubscriptionsFromDB(userId));
    }
    else
    {
        return Response.status(Status.UNAUTHORIZED).build();
    }
}

You might want to have a look on Apache Shiro which has pretty decent permission based authorization support.

You additionally might want to have a look on best practices for naming your REST resources.

Upvotes: 1

Related Questions