0

我正在使用带有 spring security 的 JWT 来处理我的 REST API 端点的授权。在以下示例中,端点提供有关用户的信息。假设我希望只有ADMIN用户能够获取所有用户的详细信息,任何其他用户都应该只获取他/她的帐户详细信息。任何人都可以想到一种更具声明性的方式来使用注释或 AOP 来实现与以下代码等效的代码。

@RequestMapping(value = "user/{userId}", method = RequestMethod.GET)
@PreAuthorize("hasAnyRole('USER', 'ADMIN')")
public UserDetailsDto getUserDetails(
        @AuthenticationPrincipal JwtUser user, 
        @PathVariable String userId) {
    if (!user.getId().equals(userId) && user.getRole != Role.ADMIN)
        throw new BadCredentialsException("Jwt token id and requested ids do not match");
    //handle the request
}
4

1 回答 1

0

您可以将在此方法上运行的 Aspect 定义为切入点引用。

  1. 在你的项目中包含 aop。(包括 apring-aop 相关的 jars,在 spring-boot 中包括 spring-boot-starter-aop。)
  2. 在您的应用程序配置中启用 AOP(使用 @EnableAspectJAutoProxy 注释注释配置类)
  3. 定义您的方面并配置之前的建议以在那里执行您的逻辑。例如:

    @Aspect
    @Component
    public class Test {
    
        @Before("execution(* com.package.name.*.getUser(..)) && args(user,dto)")
        public void getAllAdvice(JwtUser user, GetUserRequestDto dto){
            System.out.println("Service method getter called");
            if (!user.getId().equals(dto.getUserId()))
                throw new BadCredentialsException("Jwt token id and requested ids do not match");
            //handle the request
        }
    }
    

现在,您的决定应该是方面的一部分,您的业务逻辑进入您的控制器。

希望这可以帮助!!

于 2017-07-22T17:42:47.467 回答