We are using SpringBoot 3.0.5 & jakarta.validation.api:3.0.2 it is gradle project and Java is running on JDK 17
import jakarta.validation.Valid;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
@PostMapping(value = "/create")
@Operation(summary = "API used to create..., used only by the Admin", security = {@SecurityRequirement(name = "bearer-key")})
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
public ApiResponse<CreatePlmResponse> createPlm(@NotNull @Valid @RequestBody CreatePlmRequest createPlmRequest) {
Response plm = plmService.createPlm(createPlmRequest);
return ApiResponse.<CreatePlmResponse>builder()
.hasError(false)
.responseObject(mpl)
.successMessage("Successfully created an PLM for a car")
.build(); }
When we access this REST API and provide valid token with role which is not the ADMIN one it still executes the @Valid method. Shifting annotation to class level resolves the issue and we get proper 403, but having it in the attribute part the code is executed even tho the user is not allowed to get to this part of code.
This way it works perfectly fine, we are getting 403 with invalid role.
@Valid
public class PlmController {
@PostMapping(value = "/create")
@Operation(summary = "API used to create..., used only by the Admin", security = {@SecurityRequirement(name = "bearer-key")})
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
public ApiResponse<CreatePlmResponse> createPlm(@NotNull @RequestBody CreatePlmRequest createPlmRequest) {
Response plm = plmService.createPlm(createPlmRequest);
return ApiResponse.<CreatePlmResponse>builder()
.hasError(false)
.responseObject(mpl)
.successMessage("Successfully created an PLM for a car")
.build(); }}
Comment From: wilkinsona
Duplicates #10157.