io.jsonwebtoken.MalformedJwtException: JWT strings must contain exactly 2 period characters. Found: 4
at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:235)
at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:481)
at io.jsonwebtoken.impl.DefaultJwtParser.parseClaimsJws(DefaultJwtParser.java:541)
at br.com.alura.aluraflix.config.security.TokenService.isTokenValid(TokenService.java:38)
at br.com.alura.aluraflix.config.security.AuthenticationByTokenFilter.doFilterInternal(AuthenticationByTokenFilter.java:29)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
Estou recebenco essa exception,
//Filtro chamado uma única vez a cada requisição
public class AuthenticationByTokenFilter extends OncePerRequestFilter {
//não é possível fazer injeção de dependências aqui
private TokenService tokenService;
public AuthenticationByTokenFilter(TokenService tokenService) {
this.tokenService = tokenService;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String token = recuperateToken(request);
boolean valid = tokenService.isTokenValid(token);
System.out.println(valid);
filterChain.doFilter(request, response);
}
private String recuperateToken(HttpServletRequest request) {
String token = request.getHeader(HttpHeaders.AUTHORIZATION);
if(token == null || token.isEmpty() || !token.startsWith("Bearer ")){
return null;
}
return token.substring(7, token.length());
}
}
@Service
public class TokenService {
//@Value serve para injetar parâmetros do application.properties
@Value("${aluraflix.jwt.expiration}")
private String expiration;
@Value("${aluraflix.jwt.secret}")
private String secret;
public String generateToken(Authentication authentication) {
User tokenOwner = (User) authentication.getPrincipal();
Date today = new Date();
Date dataExpiration = new Date(today.getTime() + Long.parseLong(expiration));
return Jwts.builder()
.setIssuer("AluraFlix API")
.setSubject(tokenOwner.getId().toString())
//data de geração de token
.setIssuedAt(today)
.setExpiration(dataExpiration)
.signWith(SignatureAlgorithm.HS256, secret)
.compact();
}
public boolean isTokenValid(String token) {
try{
Jwts.parser().setSigningKey(this.secret).parseClaimsJws(token);
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}