buenos dîas llevo varios dîas tratando de solucionar el siguiente error y no he podido.
el filtro esta siendo llamado eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJoZW5kZXIudmVsYXNjbyIsImlzcyI6InZvbGwgbWVkIiwiaWQiOjIsImV4cCI6MTczNTg2Nzk0Mn0.vzZoykCef6xit3dPq0HvA3aS2Hvp1xMQViZWAJ3_1iw 2025-01-02T20:16:15.331-05:00 ERROR 15848 --- [api] [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
java.lang.NullPointerException: Cannot invoke "med.voll.api.infra.security.TokenService.getSubject(String)" because "this.tokenService" is null at med.voll.api.infra.security.SecurityFilter.doFilterInternal(SecurityFilter.java:31) ~[classes/:na]
@Component
public class SecurityFilter extends OncePerRequestFilter {
@Autowired
private TokenService tokenService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
System.out.println("el filtro esta siendo llamado");
//obtener el token del header
var token = request.getHeader("Authorization");
if (token == null || token == ""){
throw new RuntimeException("El token enviado no es valido");
}
token = token.replace("Bearer ", "");
System.out.println(token);
System.out.println(tokenService.getSubject(token));
filterChain.doFilter(request, response);
}
}
@Service
public class TokenService {
@Value("${api.security.secret}")
private String apiSecret;
public String generarToken(Usuario usuario){
try {
Algorithm algorithm = Algorithm.HMAC256(apiSecret);
return JWT.create()
.withIssuer("voll med")
.withSubject(usuario.getLogin())
.withClaim("id", usuario.getId())
.withExpiresAt(generarFechaExpiracion())
.sign(algorithm);
}catch (JWTCreationException exception){
throw new RuntimeException();
}
}
public String getSubject(String token) {
DecodedJWT verifier = null;
try {
Algorithm algorithm = Algorithm.HMAC256(apiSecret);
verifier = JWT.require(algorithm)
.withIssuer("voll med")
.build()
.verify(token);
verifier.getSubject();
} catch (JWTVerificationException exception) {
System.out.println(exception.toString());
}
if (verifier.getSubject()== null ) {
throw new RuntimeException("Verifier invalido");
}
return verifier.getSubject();
}
private Instant generarFechaExpiracion(){
return LocalDateTime.now().plusHours(2).toInstant(ZoneOffset.of("-05:00"));
}
}
me podrian ayudar gracias!