Hola buen día, te muestro como lo trate de hacer:
@PostMapping()
@Secured("ROLE_ADMIN")
public ResponseEntity<DoctorResponseData> registerDoctor(@RequestBody @Valid MedicalRecordData medicalRecordData,
UriComponentsBuilder uriComponentsBuilder) {
Doctor doctor = new Doctor(medicalRecordData);
doctor = repository.save(doctor);
DoctorResponseData doctorResponseData = new DoctorResponseData(
doctor.getId(),
doctor.getName(),
doctor.getEmail(),
doctor.getPhone(),
doctor.getDocument(),
new DataAddress(doctor.getAddress().getStreet(), doctor.getAddress().getDistrict(),
doctor.getAddress().getCity(), doctor.getAddress().getNumber(),
doctor.getAddress().getAddition()));
final Boolean active = doctor.getActive();
URI url = uriComponentsBuilder.path("/api/v1/doctors/{id}").buildAndExpand(doctor.getId()).toUri();
return ResponseEntity.created(url).body(doctorResponseData);
}
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfiguration {
private final SecurityFilter securityFilter;
public SecurityConfiguration(SecurityFilter securityFilter) {
this.securityFilter = securityFilter;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.csrf(csrf -> csrf.disable())
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.POST, "/login").permitAll()
.requestMatchers(HttpMethod.POST, "/api/v1/doctors").hasRole("ADMIN")
.requestMatchers(HttpMethod.PUT, "/api/v1/doctors/{id}").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/api/v1/doctors/{id}").hasRole("ADMIN")
.requestMatchers(HttpMethod.GET, "/api/v1/doctors").hasAnyRole("ADMIN", "USER")
.anyRequest().authenticated()) // Cualquier otra solicitud requiere autenticación
.addFilterBefore(securityFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Si le suprimo: //@Secured("ROLE_ADMIN") a mi Controller, si carga los datos....