Tenho uma aplicação cliente (Angular2) que envia um header com um token jwt, acontece que meus filtros parecem executar duas vezes na mesma requisição, e a primeira o header ta sempre null, na segundo consigo recuperar o token normalmente, como corrigir isso ?
public class SecurityConfig extends WebSecurityConfigurerAdapter
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/home").permitAll()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.antMatchers(HttpMethod.GET, "/doc/listar/**").hasRole("USER")
.antMatchers(HttpMethod.GET, "/doc/enviar/**").hasRole("USER")
.antMatchers(HttpMethod.GET, "/doc/autenticar/**").hasRole("USER")
.antMatchers(HttpMethod.GET, "/doc/excluir/**").hasRole("USER")
.anyRequest().authenticated()
.and()
.addFilterBefore(new CORSFilter(), ChannelProcessingFilter.class)
.addFilterBefore(new JWTLoginFilter("/login", authenticationManager(),tokenAuthenticationService),
UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new JWTAuthenticationFilter(tokenService),
UsernamePasswordAuthenticationFilter.class);
}
//Filtro que verifica o token
public class JWTAuthenticationFilter extends GenericFilterBean
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
try {
Authentication authentication = tokenAuthenticationService.getAuthentication((HttpServletRequest) req);
if(authentication != null){
SecurityContextHolder.getContext().setAuthentication(authentication);
if(authentication != null && !authentication.isAuthenticated()){
SecurityContextHolder.clearContext();
((HttpServletResponse) res).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}else {
chain.doFilter(req, res);
}
}
} catch (AuthenticationException | JwtException e) {
SecurityContextHolder.clearContext();
((HttpServletResponse) res).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
}
Método que verifica o token
public Authentication getAuthentication(HttpServletRequest request) {
String token = request.getHeader(HEADER_STRING);
//Verificar se esta nulo (primeira execuçãp sempre nulo)
if (token != null) {
if(token.isEmpty()) {
return new UsernamePasswordAuthenticationToken(token, token);
}
String user = Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
.getBody()
.getSubject();
if (user != null) {
return new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList());
}
}
return null;
}