Consigo recuperar o token, porém no teste o mesmo volta sempre como false. Conferi com alguns outros erros no fórum, como a falta de exclamação ou o tempo no properties mas estão como descrito na aula.
package br.com.alura.forum.config.security;
import java.util.Date;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import br.com.alura.forum.modelo.Usuario;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
@Service
public class TokenService {
@Value("${forum.jwt.expiration}")
private String expiration;
@Value("${forum.jwt.secret}")
private String secret;
public String gerarToken(Authentication authentication) {
Usuario logado = (Usuario) authentication.getPrincipal();
Date hoje = new Date();
Date dataExpiracao = new Date(hoje.getTime() + Long.parseLong(expiration));
return Jwts.builder()
.setIssuer("API do Fórum da Alura")
.setSubject(logado.getId().toString())
.setIssuedAt(hoje)
.setExpiration(dataExpiracao)
.signWith(SignatureAlgorithm.HS256, secret)
.compact();
}
public boolean isTokenValido(String token) {
try {
Jwts.parser().setSigningKey(this.secret).parseClaimsJws(token);
return true;
} catch (Exception e) {
return false;
}
}
public Long getIdUsuario(String token) {
Claims claims = Jwts.parser().setSigningKey(this.secret).parseClaimsJws(token).getBody();
return Long.parseLong(claims.getSubject());
}
}
package br.com.alura.forum.config.security;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import br.com.alura.forum.modelo.Usuario;
import br.com.alura.forum.repository.UsuarioRepository;
public class AutenticacaoViaTokenFilter extends OncePerRequestFilter {
private TokenService tokenService;
private UsuarioRepository repository;
public AutenticacaoViaTokenFilter(TokenService tokenService, UsuarioRepository repository) {
this.tokenService = tokenService;
this.repository = repository;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String token = recuperarToken(request);
boolean valido = tokenService.isTokenValido(token);
System.out.println(valido);
if (valido) {
autenticarCliente(token);
}
filterChain.doFilter(request, response);
}
private void autenticarCliente(String token) {
Long idUsuario = tokenService.getIdUsuario(token);
Usuario usuario = repository.findById(idUsuario).get();
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(usuario, null, usuario.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
}
private String recuperarToken(HttpServletRequest request) {
String token = request.getHeader("Authorization");
if (token == null || token.isEmpty() || !token.startsWith("Bearer ")) {
return null;
}
return token.substring(7, token.length());
}
}