javaspring-bootmultipartform-data

Spring boot access multipart request (file upload) headers before request completes


Is there a way I can check the Authorization header before the request completes? I do not want to start accepting the file upload if the user is not authenticated. My code is:

  @PostMapping(path = "/uploadLogo", produces = "application/json", consumes = "multipart/form-data")
    public ApiResponse handleFileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request){
  System.out.println(request.getHeader("Authorization")); 
  ...

This works only after the file is uploaded.


Solution

  • You can use HTTP filters. But this won't avoid the file being uploaded. The HTTP filters will intercept the request before reaching the controller. If you think the request is correct (with the adequate credentials) you continue to the controller, otherwise, throw an exception.

    I share you my repository where I've implemented the authentication via JWT on the HTTP filters: https://github.com/serlesen/backend-social-network/tree/chapter_3