0

He estado intentando implementar Spring security con Jwt pero tengo un problema persistente con la implementación del Bean relacionado con AthenticationManager, mi implementación de la configuración es la siguiente:

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class Config implements WebMvcConfigurer {

    String[] apiPublic = {
            "api/v1/user/login"
    };

    @Autowired
    private JwtAuthFilter jwtAuthFilter;

    @Bean
    PasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(HttpSecurity http, UserDetailsService userDetailsService)
            throws Exception {
        return http.getSharedObject(AuthenticationManagerBuilder.class)
                .userDetailsService(userDetailsService)
                .passwordEncoder(bCryptPasswordEncoder())
                .and()
                .build();
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            public void addCorsMappings(final CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("*").allowedMethods("*").allowedHeaders("*").maxAge(3600L);
            }
        };
    }

    @Bean
    SecurityFilterChain filterChain(final HttpSecurity http) throws Exception {
        http
                .cors().and()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeHttpRequests()
                .requestMatchers(apiPublic).permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

}

El proceso de registro se realiza perfectamente con la clave encriptada pero el login me da Forbidden, esta es la implementación del login desde el controlador:

@RestController
@RequestMapping("api/v1/user")
@RequiredArgsConstructor
public class UserController {

    private final AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/create")
    public ResponseEntity<Response> createUser(@Valid @RequestBody UserRequest request) {
        User user = userMapper.toEntity(request);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.save(user);
        return new ResponseEntity<Response>(
                new Response(false, "User created", "200-OK"),
                HttpStatus.OK);
    }

    @PostMapping("/login")
    public ResponseEntity<Response> login(@Valid @RequestBody UserRequest request) {
        return loguear(request);
    }

    private ResponseEntity<Response> loguear(UserRequest request) {
        UsernamePasswordAuthenticationToken authenticationToken = UsernamePasswordAuthenticationToken.unauthenticated(request.getUsername(), request.getPassword());
        this.authenticationManager.authenticate(authenticationToken);
        UserDetails userDetails = userDetailsService.loadUserByUsername(request.getUsername());
        System.out.println(userDetails.getUsername());
        String token = jwtUtil.createToken(userDetails);
        System.out.println(token);
        return new ResponseEntity<>(
                new Response(false, token, "200-OK"),
                HttpStatus.OK);
    }
}

Y esta es la implementación de UserDetailsSerive:

@Service
public class UserServiceImp implements UserService, UserDetailsService{

    @Autowired
    private UserRepository userRepository;

    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }

    @Override
    public User findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    @Override
    public User findById(Long id){
        return userRepository.findById(id).orElse(null);
    }

    @Override
    public void save(User user) {
       userRepository.save(user);
    }

    @Override
    public void delete(User user) {
       userRepository.delete(user);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        
      if (user == null) {
         throw new UsernameNotFoundException("User didn't find");
      }

      return new org.springframework.security.core.userdetails.User(user.getUsername() , user.getPassword() , false, false, false, false, null);
    }
    
}

Estoy usando Spring 3.1.1, el uso de and() está deprecado por las funciones lambda pero no creo que eso sea motivo para que el código no trbaje correctamente.

1 respuesta 1

0

a ver te cuento. el implements WebMvcConfigue esta deprecado. te muestro como lo tengo configurado yo.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig {

    @Autowired
    private JwtPuntoDAutentificacion jwtAuthenticationEntryPoint;
    @Autowired
    private JwtRequestFilter jwtRequestFilter;

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
            throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    public SecurityFilterChain configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.cors().and().csrf().disable().authorizeHttpRequests().antMatchers("/autenticacion/login").permitAll()
                .antMatchers("/swagger-ui/**", "/swagger-ui.html", "/v3/api-docs/**").permitAll().anyRequest()
                .authenticated().and().exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class).csrf().disable();

        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();
    }

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info().title("Servidor Medico").description("Descripción de tu API").version("1.0"));
    }

    @Bean
    public GroupedOpenApi customApiDocs() {
        return GroupedOpenApi.builder().group("Tu grupo de API").pathsToMatch("/**") // Cambiar a las rutas que quieras
                                                                                        // documentar
                .build();
    }
}

este es el controller

@RestController @CrossOrigin @RequestMapping("/autenticacion") public class AutenticacionController {

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private JwtToken jwtToken;

@Autowired
private ServiciosJwtUsuarios jwtUserDetailsService;

@Autowired
private ServiciosMedico sMedico;

@Autowired
private ServiciosPaciente sPaciente;

@PostMapping("/login")
public ResponseEntity<JwtResponse> createAuthenticationToken(@RequestBody Map<String, String> request)
        throws Exception {
    String identificador = request.get("identificador").toLowerCase();
    String password = request.get("password");
    authenticate(identificador, password);
    final UserDetails userDetails = jwtUserDetailsService.loadUserByUsername(identificador);
    String token = "";
    if (identificador.toUpperCase().startsWith("M")) {
        Optional<Medico> optMedico = sMedico.buscarMedico(identificador);
        if (optMedico.isPresent()) {
            token = jwtToken.generarToken(userDetails, optMedico.get());
        }
    } else if (identificador.toUpperCase().startsWith("ES")) {
        Optional<Paciente> optPaciente = sPaciente.buscarPaciente(identificador);
        if (optPaciente.isPresent()) {
            token = jwtToken.generarToken(userDetails, optPaciente.get());
        }
    }
    if (token.isEmpty()) {
        throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Usuario no encontrado");
    }
    return ResponseEntity.ok(new JwtResponse(token));
}

protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.csrf().disable().authorizeHttpRequests().antMatchers("/autenticacion/**").permitAll().anyRequest()
            .authenticated().and().exceptionHandling().and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

@Transactional
private void authenticate(String username, String password) throws Exception {
    try {
        authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
    } catch (DisabledException e) {
        throw new Exception("USER_DISABLED", e);
    } catch (BadCredentialsException e) {
        throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Credenciales invalidas");
    }
}

} un dto

  public class JwtRequest implements Serializable {

    private static final long serialVersionUID = 11L;
    private String identificador;
    private String password;

otro

public class JwtResponse implements Serializable {

    private static final long serialVersionUID = 12L;
    private final String jwttoken;

    public JwtResponse(String jwttoken) {
        this.jwttoken = jwttoken;
    }

    public String getJwttoken() {
        return this.jwttoken;
    }

el servicio

   @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;
    }
}

Por si quieres echar un vistazo el proyecto https://github.com/carlos033/ServicorRestConJjwt

1
  • 1
    El problema era en el metodo loadByUsername, no estaba pasandole las authorities al user, tu proyecto me ayudo a encontrar mi error, gracias bro
    – Camilo
    Commented el 29 jun. 2023 a las 19:45

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.