0

I have a requirement where I need to call aspect before processing the rest endpoint method, I have created an annotation and annotating the rest endpoint,

I am able to process the request but when reading InpuStream it is already closed inseide aspect. The code snippet is attached I am using spring boot 1.5

GitHub https://github.com/primeap/user-auth-poc.git

Once I get input stream in the Aspect I will cache it before using it, but my problem is at the current code it is throwing an

io exception stream is closed

at line

Map jsonMap = mapper.readValue(request.getInputStream(), Map.class);

Application

@SpringBootApplication
@ComponentScan(basePackages = { "org.ap" })
public class UserAuthPocApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserAuthPocApplication.class, args);
    }
}

Annotation

@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface HasPrivilegeXX {

}

Aspect

@Aspect
@Component
public class MyPrivilegeAspect {
    @Before("@annotation(HasPrivilegeXX)")
    public boolean logBeforeAllMethods(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
                .getRequest();
        try {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> jsonMap = mapper.readValue(request.getInputStream(), Map.class);
            System.out.println("In aspect " + jsonMap.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}

Rest Endpoint

@RestController
@RequestMapping("/api")
public class Api {
    @PostMapping("/hi")
    @HasPrivilegeXX()
    public String hiPost(@RequestBody User user) {
        System.out.println(user.toString());
        return "Hi...";
    }
}

User

public class User {
    private String name;
    private String company;
    private Integer id;
}
Arvind
  • 1,207
  • 6
  • 27
  • 55
  • 1
    You cannot simply read from the request as you can only read it once. So if you read it like this either downstream (in the controller) it would fail or it fails at your position because it already was read. You can only do this in. filter by wrapping the request so that you can read it multiple times. – M. Deinum Oct 31 '18 at 06:37
  • Thanks, I will check, is there a document which tells that – Arvind Oct 31 '18 at 08:01
  • 1
    Check this link if you want to intercept the entpoints https://stackoverflow.com/questions/35232597/how-to-intercept-all-requests-in-spring-rest-controllers – Deepak Gunasekaran Oct 31 '18 at 08:18
  • I have used Filter and got the input stream.... thanks a lot – Arvind Oct 31 '18 at 10:43

0 Answers0