wener
wener

Reputation: 7750

Spring security RESTful path based role control

e.g.

/user/{userId}/* # Only user with userId and admin can access
/order/{orderId}/* # Only the order owner of orderId and admin can access

Current solution, the @Current annotation is a customized injection which is relate to the token passed to server.@PathVariable("user-id") UserEntity user is got from path with Spring-Data

@PreAuthorize("#user.id == #u?.id")
public UserDTO access(@P("user") @Current UserEntity requestUser,
                      @P("u") @PathVariable("user-id") UserEntity user)

@PreAuthorize("#user.id == #uid && (#order == null || #order?.user?.id == #uid)")
public Message access(@Current @P("user") UserEntity user,
                      @PathVariable("user-id") @P("uid") Long uid,
                      @PathVariable("order-id") @P("order") OrderEntity order)

We got too many annotation, is there any simple way to config them all ?

Tried

  1. Use .antMatchers("/user/[0-9]+/*").hasRole("ROLE_USER") can not customize the user check.
  2. AOP, too complicated, can no do url based.

Upvotes: 0

Views: 147

Answers (1)

davioooh
davioooh

Reputation: 24676

I suggest you to use method security to implement fine grained logic to auhtorize resource access. Url-based authentication in my opinion is effective only for simple use cases.

I would also suggest to use AOP with custom annotations to implement your method security (instead of using @PreAuthorize) if your authorization logic requires several lines of code...

For example you could intercept annotated method invocations:

@Before("@annotation(your.annotations.AllowedToOwner) && @annotation(ann)")
public void checkOwner(JoinPoint joinPoint, AllowedToOwner ann) throws Throwable {

    // check owner, throws AccessDeniedException if check fails...
}

Upvotes: 1

Related Questions