来自请求参数的JWT Spring安全用户授权

时间:2017-04-05 19:24:11

标签: rest spring-security spring-aop spring-restcontroller spring-security-rest

我正在使用带有Spring安全性的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
}

1 个答案:

答案 0 :(得分:0)

您可以将此方法上运行的Aspect定义为切入点参考。

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

    @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
        }
    }
    
  4. 现在,您的决定应该是方面的一部分,您的业务逻辑将进入您的控制器。

    希望这会有所帮助!!

相关问题