Reputation: 13
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.
Upvotes: 1
Views: 1635
Reputation: 1164
This is probably a late answer but you can enable the required behavior with the Spring configuration:
/**
* Whether to resolve the multipart request lazily at the time of file or parameter
* access.
*/
spring.servlet.multipart.resolve-lazily: true|false
Example:
Spring security config:
...
.requestMatchers("/v1/admin/files/**").hasRole("ADMIN")
Spring multipart config:
spring.servlet.multipart.max-file-size: 10GB
spring.servlet.multipart.max-request-size: 10GB
Dummy endpoint:
@PostMapping(path = "/upload")
public ResponseEntity<Void> upload(@RequestParam("file") MultipartFile file) {
return ResponseEntity.ok().build();
}
And the test request with a basic auth (from the postman):
curl --location 'http://127.0.0.1:8080/v1/admin/files/upload' \
--header 'Authorization: ••••••' \
--form 'file=@"/C:/test/file.zip"'
As a result the request with 2GB file and correct credentials takes around 9.04 sec here (response is 200), and 33 ms for the wrong credentials (response is 401)
Upvotes: 0
Reputation: 1629
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
Upvotes: 0