Solucionado (ver solução)
Solucionado
(ver solução)
1
resposta

Após o termino do curso só consigo gerar o Token, para todas as outras requisições recebo "403 Forbidden"

2023-02-27T16:51:33.438-03:00  INFO 20400 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-02-27T16:51:33.438-03:00  INFO 20400 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2023-02-27T16:51:33.439-03:00  INFO 20400 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
Chamado filter
Hibernate:
    select
        u1_0.id,
        u1_0.login,
        u1_0.senha
    from
        usuarios u1_0
    where
        u1_0.login=?
Chamado filter
2023-02-27T16:52:09.497-03:00 ERROR 20400 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception

java.lang.RuntimeException: Token inválido ou  expirado!
    at br.com.jards.med.voll.infra.security.TokenService.getSubject(TokenService.java:45) ~[classes/:na]
    at br.com.jards.med.voll.infra.security.SecurityFilter.doFilterInternal(SecurityFilter.java:34) ~[classes/:na]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.4.jar:6.0.4]
@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 ex) {
            throw new RuntimeException("Erro ao gerar o Token JWT: ", ex);
        }
    }

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

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

    @Autowired
    private SecurityFilter securityFilter;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http.csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().authorizeHttpRequests()
                .requestMatchers(HttpMethod.POST, "/login").permitAll()
                .anyRequest().authenticated()
                .and().addFilterBefore(securityFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }

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

    @Bean
    public PasswordEncoder nameEncoder() {
        return new BCryptPasswordEncoder();
    }
}
public class SecurityFilter extends OncePerRequestFilter {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UsuarioRepository repository;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

                System.out.println("Chamado filter");
        var tokenJWT = recuperarTokenJWT(request);

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

            SecurityContextHolder.getContext().setAuthentication(authentication);
            System.out.println("Logado na requisição!");
        }

        chain.doFilter(request, response);
    }

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

        return null;
    }
}
1 resposta
solução!

Resolvido:

private String recuperarTokenJWT(HttpServletRequest request) {
        var authorizationHearder = request.getHeader("Authorization");
        if (authorizationHearder != null) {
            return authorizationHearder.replace("Bearer ", ""); //Estava faltando o espaço depois do Bearer
        }

        return null;
    }