2016-08-05 72 views
0

例如Spring安全性基于REST风格的角色控制

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

当前解决方案中,@Current注释是一个定制的注射是涉及token传递给服务器。 @PathVariable("user-id") UserEntity user从路径得到了与Spring的数据

@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) 

我们得到了太多的诠释,有没有简单的方法来配置他们呢?

试图

  1. 使用.antMatchers("/user/[0-9]+/*").hasRole("ROLE_USER")不能自定义的用户检查。
  2. AOP太复杂了,根本无法做到网址。

回答

1

我建议你使用方法安全性来实现细粒度的逻辑来实现资源访问。在我看来,基于网址的身份验证仅对简单用例有效。

我也建议使用AOP自定义注释来实现你的方法的安全性(而不是使用@PreAuthorize)如果您的授权逻辑需要几行代码...

例如,你可以截获标注的方法调用:

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

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

也许这只是可行的方法。 – wener

+0

@wener这是我通常应用于我的项目的方法。也许有更好的方法来实现你想要的,但我发现这种方法非常可读和有效。 – davioooh