vi as soluções dos topicos anteriores com o mesmo tema mas não consegui resolver.
`@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) {
if (token == null || token.trim().isEmpty()) {
return false;
}
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);
System.out.println(token);
boolean valido = tokenService.isTokenValido(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 SecurityConfigurations extends WebSecurityConfigurerAdapter {
@Autowired
private AutenticacaoService autenticacaoService;
@Autowired
private TokenService tokenService;
@Override
@Bean
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
// configura a autenticação. (login)
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(autenticacaoService).passwordEncoder(new BCryptPasswordEncoder());
}
// configura a autorização. (acesso de perfis a determinados métodos/url)
@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);
}
// configura recursos estáticos (js,css,imagens, etc..)
@Override
public void configure(WebSecurity web) throws Exception {
}
}