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

por que esta dando erro no token service

meu lombok tava dando erro, fiz a instalação dele pelo plugin e agora estou tendo isso

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'JWT_SECRET' in value "${JWT_SECRET}" Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tokenservice': Injection of autowired dependencies failed Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'filtersecurity': Unsatisfied dependency expressed through field 'tokenservice': Error creating bean with name 'tokenservice': Injection of autowired dependencies failed org.springframework.context.ApplicationContextException: Unable to start web server

import com.example.demo.repository.UsuarioRepositorio; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component public class Filtersecurity extends OncePerRequestFilter { @Autowired private Tokenservice tokenservice; @Autowired private UsuarioRepositorio repository; @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 = repository.findByLogin(subject);

        var authentication = new UsernamePasswordAuthenticationToken(Usuario, null, Usuario.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
    filterChain.doFilter(request,response);

}

private String recuperarToken(HttpServletRequest request) {
    var authorization = request.getHeader("Authorization");
    if (authorization == null || !authorization.startsWith("Bearer ")) {
        return null;
    }
    return authorization.replace("Bearer ", "").trim();
}

} package com.example.demo.infra.securityconfiguration;

import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; import com.auth0.jwt.exceptions.JWTVerificationException; import com.example.demo.domain.objeto.Usuario; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service;

import javax.management.RuntimeMBeanException; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.Date;

@Service public class Tokenservice { @Value("${api.security.token.secret}") private String secret; public String gerartoken(Usuario usuario){

    try {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        return  JWT.create()
                .withIssuer("API chat")
                .withSubject(usuario.getLogin())
                .withExpiresAt(Date.from(DataExpiracao()))
                .sign(algorithm);
    } catch (JWTCreationException exception){
        throw new RuntimeException("erro ao gerar chave", exception);
    }
}
public String getsubject(String tokenJWT){
    try {
        var algoritmo = Algorithm.HMAC256(secret);
        return JWT.require(algoritmo)
                .withIssuer("API chat")
                .build()
                .verify(tokenJWT)
                .getSubject();
    } catch (JWTVerificationException exception) {
        throw new RuntimeException("Token JWT inválido ou expirado!");
    }
}
private Instant DataExpiracao() {
    return LocalDateTime.now().plusHours(2).toInstant(ZoneOffset.of("-03:00"));
}

}

3 respostas

spring.application.name=chat spring.datasource.url=jdbc:mysql://localhost/chat spring.datasource.username=root Spring.datasource.password=Efds11091999.# spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.show-jpa=true spring.jpa.properties.hibernate.format_sql=true spring.jpa.hibernate.ddl-auto=update spring.flyway.enabled=true spring.flyway.locations=classpath:db/migration flyway.baseline-on-migrate=true flyway.locations=classpath:db/migration server.error.include-stacktrace=never api.security.token.secret=${JWT_SECRET}

package com.example.demo.infra.securityconfiguration;

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration @EnableWebSecurity public class SecurityConfig { @Autowired private Filtersecurity securityfilter;

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

    http
            .csrf(csrf -> csrf.disable()) // Desativa a proteção CSRF
            .sessionManagement(session -> session
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

            )
            .authorizeHttpRequests(requests -> requests
                    .requestMatchers(HttpMethod.POST, "/usuario").permitAll() // Permite acesso não autenticado ao POST /usuario
                    .anyRequest().authenticated() // Requer autenticação para todas as outras requisições

            )

            .addFilterBefore(securityfilter, UsernamePasswordAuthenticationFilter.class);
    return http.build();
}



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

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

}

solução!

resolvi, o erro era pq no aplication.proprieties eu não tinha colocado nenhum valor no JWT_SECRET