Solucionado (ver solução)
Solucionado
(ver solução)
4
respostas

[Dúvida] Header Authorization vem null no doFilterInternal

Caros,

Minha aplicacao em Vue envia uma requisicao para a aplicacao em Spring Boot 3 (Spring Security + JWT).

O Token é gerado corretamente e enviado, porém no Filter ele nao consegue ler o hearder Authorization porque esta nulo.

Já coloquei .cors.disable, já coloquei o cors configuration, porem nao funciona.

Eu li no stackoverflow que poderia ser por que eu rodas as duas aplicacoes no endereco localhost, porem com portas diferentes. Porem, eu nao entendi qual solucao eu poderia dar.

@Component public class AuthenticationFilter extends OncePerRequestFilter{

private TokenService tokenService;    
private UserRepository userRepository;

public AuthenticationFilter(TokenService tokenService, UserRepository userRepository) {
    this.tokenService = tokenService;
    this.userRepository = userRepository;
}

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {

    String token = this.retrieveToken(request);

    if (tokenService.isTokenValid(token)) {
        String username = tokenService.getUsername(token);

        Optional<User> user = userRepository.findByUsername(username);

        System.out.println(user.get().getUsername());

        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                user.get(), null, user.get().getAuthorities());

        authentication.setDetails(
                    new WebAuthenticationDetailsSource().buildDetails(request)
            );
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    filterChain.doFilter(request, response);

}

private String retrieveToken(HttpServletRequest request) {
    String token = request.getHeader("Authorization");

    if (token == null || token.isEmpty() || token.startsWith("Bearer") ) {
        return null;
    }

    return token.substring(7, token.length());
}

}

@Configuration @EnableWebSecurity public class SecurityConfigurations {

@Autowired
private TokenService tokenService;

@Autowired
private UserRepository userRepository;

@Bean
public UserDetailsService userDetailService() {
    return new AuthService();
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    return http.csrf().disable()
            .authorizeHttpRequests()
            .requestMatchers(HttpMethod.POST, "/auth").permitAll()
            .and()
            .authorizeHttpRequests()
            .requestMatchers(HttpMethod.GET, "/api/**").authenticated()
            .and()
            .cors()
            .and().addFilterBefore(new AuthenticationFilter(tokenService, userRepository), UsernamePasswordAuthenticationFilter.class)
            .authenticationProvider(authenticationProvider())
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .build();        
}
@Bean
public AuthenticationProvider authenticationProvider(){
    DaoAuthenticationProvider authenticationProvider=new DaoAuthenticationProvider();
    authenticationProvider.setUserDetailsService(userDetailService());
    authenticationProvider.setPasswordEncoder(passwordEncoder());
    return authenticationProvider;
}


@Bean
public AuthenticationManager authManager(HttpSecurity http) throws Exception {
    return http.getSharedObject(AuthenticationManagerBuilder.class)
        .authenticationProvider(authenticationProvider())
        .build();
}

@Bean
public PasswordEncoder passwordEncoder() {
    return new PasswordEncoder() {
        @Override
        public String encode(CharSequence charSequence) {
            return getMd5(charSequence.toString());
        }

        @Override
        public boolean matches(CharSequence charSequence, String s) {
            return getMd5(charSequence.toString()).equals(s);
        }
    };
}
@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source =
        new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    config.setAllowedOrigins(Arrays.asList("http://localhost:8080"));
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}
4 respostas

Oi Elaine!

Se está retornando null é porque o cabeçalho não está vindo na requisição. Confere no seu código da aplicação Vue se o header Authorization está de fato sendo enviado nas requisições.

Oi Rodrigo, obrigada por responder. Mas o Vue esta enviando sim:

Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJBUEkgRXVwcm8gT3ZlcnZpZXciLCJzdWIiOiJlbGFpbmUiLCJpYXQiOjE2NzYwMzc4OTUsImV4cCI6MTY3NjEyNDI5NX0.MNfmbGnKosVaXS-gADkgFiLo8w2Yd13iz_F80AYyenQ
Connection: keep-alive
Host: localhost:8085
Origin: http://localhost:8080
Referer: http://localhost:8080/
sec-ch-ua: "Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
token: eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJBUEkgRXVwcm8gT3ZlcnZpZXciLCJzdWIiOiJlbGFpbmUiLCJpYXQiOjE2NzYwMzc4OTUsImV4cCI6MTY3NjEyNDI5NX0.MNfmbGnKosVaXS-gADkgFiLo8w2Yd13iz_F80AYyenQ
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36

Vue

getQuantityOfOrders(){
        let token=localStorage.getItem("token");
        token = JSON.parse(token);
        http.defaults.headers.common['Authorization'] = `Bearer ${token.token}`;
        return http.get("/quantityOfOrders", {
            headers: {
                Authorization: `Bearer ${token.token}`,
                token: token.token

            }});
    }
solução!

Perfeito!

Na verdade tem um errinho nesse seu if da classe filter:

if (token == null || token.isEmpty() || token.startsWith("Bearer") ) {
    return null;
}

A última expressão deveria estar negada: !token.startsWith("Bearer")

if (token == null || token.isEmpty() || !token.startsWith("Bearer") ) {
    return null;
}

Muito obrigada Rodrigo !