Professor, bom dia! Minha aplicação está dando um erro de Bad Resquest. Não estou conseguindo logar na aplicação, diz que o usuário está nulo. Consegue me ajudar, por gentileza?
org.springframework.security.authentication.InternalAuthenticationServiceException: UserDetailsService returned null, which is an interface contract violation
public class SecurityFilter extends OncePerRequestFilter {
@Autowired
private TokenService tokenService;
@Autowired
private UserRepository repository;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
var tokenJWT = recoveryToken(request);
if (tokenJWT != null){
var subject = tokenService.getSubject(tokenJWT);
var user = repository.findByLogin(subject);
var authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(request, response);
}
private String recoveryToken(HttpServletRequest request) {
var authorizationHeader = request.getHeader("Authorization");
if (authorizationHeader != null) {
return authorizationHeader.replace("Bearer ", "");
}
return null;
}
}
@Configuration
@EnableWebSecurity
public class SecurityConfigurations {
@Autowired
private SecurityFilter securityFilter;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.csrf(csrf -> csrf.disable())
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(req -> {
req.requestMatchers(HttpMethod.POST, "/login").permitAll();
req.anyRequest().authenticated();
})
.addFilterBefore(securityFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
return configuration.getAuthenticationManager();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
@Service
public class TokenService {
private static final String ISSUER = ("API Voll.med");
@Value("${api.security.token.security}")
private String secret;
public String generateToken(User user) {
try {
var algorithm = Algorithm.HMAC256(secret);
return JWT.create()
.withIssuer(ISSUER)
.withSubject(user.getLogin())
.withExpiresAt(expirateDate())
.sign(algorithm);
} catch (JWTCreationException exception){
throw new RuntimeException("Erro ao gerar token jwt", exception);
}
}
public String getSubject(String tokenJWT) {
try {
var algorithm = Algorithm.HMAC256(secret);
return JWT.require(algorithm)
.withIssuer(ISSUER)
.build()
.verify(tokenJWT)
.getSubject();
} catch (JWTVerificationException exception){
throw new RuntimeException("Token JWT inválido");
}
}
private Instant expirateDate() {
return LocalDateTime.now().plusHours(2).toInstant(ZoneOffset.of("-03:00"));
}
}