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.