Java – Rest API and resource authorization

api-designauthorizationjavarest

The way I created my rest api is the following:

/api/users/{id}
/api/users/{id}/items/{itemId}

But I also have URIs like this one:

/api/items/{itemId}

It's a bit confusing to me how to handle the item authorization in this case.

I don't want to send every request for a resource to the /api/users/{id}/items/{itemId} URI, but I also want to make sure that a user can't access an item it's not associated with.

My idea is to use AOP, and for every request to /api/items/{itemId}, get the user from the JWT authentication token, and decide whether or not the user is authorized to access the given item.

Is this approach ok, or are there better alternatives?

Best Answer

Yes, your approach is OK and commonly used.

In fact, if you model your code right, you are likely to be using the same code for access authorization for both cases anyway.

Very simplified example:

public Item getUserItem(int userId, int itemId) {
    Item item = loadItem(itemId);

    if (userId != item.ownerId()) {
        // fail, access not allowed
    }

    return item;
}

// URI: /api/users/{id}/items/{itemId}

Item getForUser(int id, int itemId) {
    return getUserItem(id, itemId);
}

--------------------------------

// URI: /api/items/{itemId}

Item get(int itemId) {
    return getUserItem(
        JwtParser.parse(headers.Authorization).userId,
        itemId
    );
}