Tengo este error
org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'webSecurityConfig': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation(DefaultSingletonBeanRegistry.java:355) ~[spring-beans-5.3.26.jar:5.3.26]
Os dejo las clases
@Service
public class ServiciosJwtUsuarios implements ServicioJwtUsuario {
@Autowired
private MedicoRepository medicoRepository;
@Autowired
private PacienteRepository pacienteRepository;
private UserDetails cargarMedicoPorIdentificador(String identificador) {
Optional<Medico> optMedico = medicoRepository.findById(identificador);
if (!optMedico.isPresent()) {
throw new UsernameNotFoundException("Usuario no encontrado con identificador: " + identificador);
}
Medico m = optMedico.get();
List<GrantedAuthority> authorities = new ArrayList<>();
return new org.springframework.security.core.userdetails.User(m.getnLicencia(), m.getPassword(), authorities);
}
private UserDetails cargarPacientePorIdentificador(String identificador) {
Optional<Paciente> optPaciente = pacienteRepository.findById(identificador);
Paciente p = optPaciente.get();
List<GrantedAuthority> authorities = new ArrayList<>();
return new org.springframework.security.core.userdetails.User(p.getnSS(), p.getPassword(), authorities);
}
@Override
public UserDetails loadUserByUsername(String identificador) {
if (identificador.startsWith("m")) {
return cargarMedicoPorIdentificador(identificador);
} else if (identificador.startsWith("es")) {
return cargarPacientePorIdentificador(identificador);
}
return null;
}
}
@Service("ServiciosMedicoI")
public class ServiciosMedico implements ServiciosMedicoI {
@Autowired
private MedicoRepository repositorioM;
@Autowired
private HospitalRepository repositorioH;
@Autowired
@Lazy
private BCryptPasswordEncoder passwordEncoder;
@Override
public List<Medico> buscarTodosM() {
return repositorioM.findAll();
}
@Override
@Transactional
public void saveMedico(Medico medico1) {
medico1.setPassword(passwordEncoder.encode(medico1.getPassword()));
repositorioM.save(medico1);
}
@Override
public void eliminarMedico(String nLicencia) throws ExcepcionServicio {
Optional<Medico> optMedico = repositorioM.findById(nLicencia);
if (!optMedico.isPresent()) {
throw new ExcepcionServicio("El numero de Licencia no existe");
}
repositorioM.deleteById(nLicencia);
}
@Override
public Optional<Medico> buscarMedico(String nLicencia) throws ExcepcionServicio {
Optional<Medico> optMedico = repositorioM.findById(nLicencia);
if (!optMedico.isPresent()) {
throw new ExcepcionServicio("El numero de Licencia no existe");
}
return optMedico;
}
@Override
public List<Paciente> BuscarPacientesXMedico(String nLicencia) throws ExcepcionServicio {
List<Paciente> listaPacientes = repositorioM.BuscarPacientesXMedico(nLicencia);
if (listaPacientes.isEmpty()) {
throw new ExcepcionServicio("El numero de Licencia no existe");
}
return listaPacientes;
}
@Override
public List<Medico> BuscarMedicoXEspecialidad(String especialidad, String hospital) throws ExcepcionServicio {
Optional<Hospital> optHospital = repositorioH.findById(hospital);
if (!optHospital.isPresent()) {
throw new ExcepcionServicio("El hospital no existe");
}
List<Medico> listaMedico = repositorioM.BuscarMedicoXEspecialidad(especialidad, hospital);
if (listaMedico.isEmpty()) {
throw new ExcepcionServicio("No hay medicos con esa especialidad");
}
return listaMedico;
}
@Override
public List<Medico> BuscarMedicosXHospital(String hospital) throws ExcepcionServicio {
List<Medico> listaMedico = repositorioM.BuscarMedicosXHospital(hospital);
if (listaMedico.isEmpty()) {
throw new ExcepcionServicio("No hay medicos en el hospital");
}
return listaMedico;
}
}
Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig {
private final JwtPuntoDAutentificacion jwtAuthenticationEntryPoint;
private final ServiciosJwtUsuarios jwtUserDetailsService;
private final JwtRequestFilter jwtRequestFilter;
public WebSecurityConfig(JwtPuntoDAutentificacion jwtAuthenticationEntryPoint,
ServiciosJwtUsuarios jwtUserDetailsService, JwtRequestFilter jwtRequestFilter) {
this.jwtAuthenticationEntryPoint = jwtAuthenticationEntryPoint;
this.jwtUserDetailsService = jwtUserDetailsService;
this.jwtRequestFilter = jwtRequestFilter;
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(jwtUserDetailsService);
provider.setPasswordEncoder(passwordEncoder());
return provider;
}
@Bean
public SecurityFilterChain configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.cors().and().csrf().disable().authorizeRequests().antMatchers("/autenticacion/login").permitAll()
.anyRequest().authenticated().and().exceptionHandling()
.authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable();
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
return httpSecurity.build();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList(new String[] { "*" }));
configuration.setAllowedMethods(
Arrays.asList(new String[] { "HEAD", "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS" }));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(Arrays.asList(new String[] { "*" }));
configuration.setExposedHeaders(Arrays.asList(new String[] { "X-Auth-Token", "Authorization",
"Access-Control-Allow-Origin", "Access-Control-Allow-Credentials" }));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
@Autowired
public void configureAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());
}
}
*/
@Component public class JwtRequestFilter extends OncePerRequestFilter {
@Autowired
private ServiciosJwtUsuarios jwtUserDetailsService;
@Autowired
private JwtToken jwtTokenUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
final String requestTokenHeader = request.getHeader("Authorization");
String identifier = null;
String jwtToken = null;
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
jwtToken = requestTokenHeader.substring(7);
try {
identifier = jwtTokenUtil.obtenerIdentificadorDelToken(jwtToken);
} catch (IllegalArgumentException e) {
logger.error("No se pudo obtener el identificador del token JWT", e);
} catch (ExpiredJwtException e) {
logger.error("El token JWT ha expirado", e);
}
}
if (identifier != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(identifier);
if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
chain.doFilter(request, response);
}
} no consigo eliminarla por mas que lo itnento