Solucionado (ver solução)
Solucionado
(ver solução)
2
respostas

Erro 403

Token service: @Service public class TokenService {

@Value("${api.security.token.secret}")
private String secret;
public String gerarToken(Usuario usuario) {
    try {
        var algoritimo = Algorithm.HMAC256(secret);
        return JWT.create()
                .withIssuer("API Voll.med")
                .withSubject(usuario.getLogin())
                .withExpiresAt(dataExpiracao())
                .sign(algoritimo);
    } catch (JWTCreationException exception){
       throw new RuntimeException("Erro ao gerar token jwt", exception);
    }
}

public String getSubject(String tokenJWT) {
    try {
        var algoritmo = Algorithm.HMAC256(secret);
        return JWT.require(algoritmo)
                .withIssuer("API Voll.med")
                .build()
                .verify(tokenJWT)
                .getSubject();
    } catch (JWTVerificationException exception) {
        throw new RuntimeException("Token JWT inválido ou expirado: " + tokenJWT);
    }
}

private Instant dataExpiracao() {
    return LocalDateTime.now().plusHours(2).toInstant(ZoneOffset.of("-03:00"));
}

}

SecurityFilter: @Component public class SecurityFilter extends OncePerRequestFilter {

@Autowired
private TokenService tokenService;
@Autowired
private UsuarioRepository usuarioRepository;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    var tokenJWT = recuperarToken(request);

   if (tokenJWT != null){
       var subject = tokenService.getSubject(tokenJWT);
       var usuario = usuarioRepository.findByLogin(subject);
       var authentication = new UsernamePasswordAuthenticationToken(usuario, null, usuario.getAuthorities());
       SecurityContextHolder.getContext().setAuthentication(authentication);

   }
    filterChain.doFilter(request,response);
}

private String recuperarToken(HttpServletRequest request) {
    var authorizationHeader=request.getHeader("Authorization");
    if(authorizationHeader != null){
        return authorizationHeader.replace("Bearer", " ");

    }
    return null;
}

}

SecurityConfigurations: @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().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();
}

}

2 respostas
solução!

Oi!

O problema está no método recuperarToken da classe SecurityFilter, nesse if:

if(authorizationHeader != null){
    return authorizationHeader.replace("Bearer", " ");
}

O espaço em branco é após a palavra Bearer:

return authorizationHeader.replace("Bearer ", "");

Obrigado!!