Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic instance-level authorization with Jersey (based on id)

Apologies as I am fairly new to Jersey. I've been trying to find a way to have instance-level access authorization using Jersey resources, but the most granularity I'm seeing is Role or static instance-level permissions. I'm a little puzzled because it

To describe better what I mean: suppose an User owns a group of Post resources - presumably this user has the role Author. I don't want every User who is an Author to be able to modify every Post, though. What is the easiest way to control this?

Is this the kind of authorization that's dealt with within the resource class method? Should I be creating a custom Authorization filter? If so, are there any examples of such a thing out there? I'm a little puzzled as it seems like such a common use case.

Thanks!

like image 438
psugar Avatar asked Jul 15 '26 13:07

psugar


1 Answers

The reason there isn't much out there in terms of examples is that it's probably down to your own data model as to how you handle this.

Taking a simple example, if each Post has an owner then your resource would probably look something like this:

@PUT
@Path("{id: [A-Fa-f0-9]+}")
@Consumes(MediaType.APPLICATION_JSON)
public T update(@Context HttpServletRequest request, final T item, @PathParam("id") final String id)
{
  final Post post = getPostbyId(id);
  if (!post.allowedToUpdate(request.getUserPrincipal())
  {
    throw new UnauthorizedException();
  }
  // Authorized, carry on
}

There are no end of variations on this theme, but if you're doing resource-level authorization you probably want to do it in something like this way, where you obtain the resource given its ID and then decide if the user is authorized to carry out the requested operation.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!