Boa tarde. Conferi os outros tópicos e por fora em outros sites, documentação, mas não consegui encontrar a resposta. Estou tendo o mesmo problema do retorno chegar como false, entrando na SignatureException.
Conferi o código várias e várias vezes, comparando com o da aula e alguns apresentados no fórum, mas posso ter deixado passar algo.
Fiz o teste no jwt.io e o token está como "Signature Verified".
Código:
@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) {
e.printStackTrace();
return false;
}
}
}
/
public class AutenticacaoViaTokenFilter extends OncePerRequestFilter {
private TokenService tokenService;
public AutenticacaoViaTokenFilter(TokenService tokenService) {
this.tokenService = tokenService;
}
@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(token);
System.out.println(valido);
filterChain.doFilter(request, response);
}
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());
}
}
/
@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private TokenService tokenService;
@Autowired
private AutenticacaoService autenticacaoService;
@Override
@Bean
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
// Configuraçoes de autenticaçao (controle de acesso, login)
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(autenticacaoService).passwordEncoder(new BCryptPasswordEncoder());
}
// Configuraçoes de autorizaçao (quem pode acessar cada URL, perfil de acesso)
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.GET, "/topicos").permitAll()
.antMatchers(HttpMethod.GET, "/topicos/*").permitAll()
.antMatchers(HttpMethod.POST, "/auth").permitAll()
.anyRequest().authenticated()
.and().csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().addFilterBefore(new AutenticacaoViaTokenFilter(tokenService), UsernamePasswordAuthenticationFilter.class);
//.and().formLogin() chama formulario de login
}
// Configuraçoes de recursos estáticos (CSS, JS)
@Override
public void configure(WebSecurity web) throws Exception {
}
}
Até esta aula, estava tudo rodando tranquilo, portanto imagino que seja especificamente algo que foi alterado nesta aula.
Estou utilizando o IntelliJ CE.
Obrigado!