Search code examples
angularnetflix-zuul

Angular 5 - httpClient is not sending headers on request


I have my angular application that is sending http request to my zuul service, my problem is that when I try to send the authorization header, the zuul service is not receiving the header, this is the angular code:

obtenerAvisos() {
    const token = localStorage.getItem('token');
    const headers = new HttpHeaders(
      {
        'Content-Type':  'application/json',
        'Authorization': token
      }
    );

    return this.http.get(
      environment.url + environment.msavisos,
      {
        headers: headers
      }
    );
  }

On zuul I created a pre filter and there I am trying to catch the header:

package com.filtro;

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.HttpStatusCodeException;
import com.netflix.zuul.context.RequestContext;
import com.utilidades.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import com.netflix.zuul.ZuulFilter;

public class PreFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public Object run() {

        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        String ip = request.getLocalAddr();
        String authorization = request.getHeader("Authorization");
        String content = request.getHeader("Content-Type");
        System.out.println(content);
        try {
            if ( request.getRequestURL().toString().contains("/usuarios/sesion")) {

            } else if ( authorization != null ) {

                Claims claims = null;

                try {
                     claims = jwtUtil.parseToken(authorization);
                 } catch (ExpiredJwtException e) {
                     // Sesion expirada
                     ctx.unset();
                     ctx.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
                 }

                if (claims != null) {
                    if (!JwtUtil.esIpCorrecta(claims, ip)) {
                        // Ip sin acceso
                        ctx.unset();
                        ctx.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
                    } else {
                        // Acceso concedido
                        ctx.addZuulRequestHeader("authorization", jwtUtil.generateToken(claims, ip));
                    }
                } else {
                    // Token Invalido
                    ctx.unset();
                    ctx.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
                }

            } else {
                ctx.unset();
                ctx.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
            }

        }  catch (HttpStatusCodeException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

I made a request using postman and send the header and everyting is working correctly, I already seen this and this but can't find an answer, can someone help me with this issue?, thanks in advance.


Solution

  • At the end the problem was zuul, I needed to add a cors configuration to my main application:

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
    import org.springframework.context.annotation.Bean;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    import org.springframework.web.filter.CorsFilter;
    import com.filtro.PostFilter;
    import com.filtro.PreFilter;
    import com.utilidades.JwtUtil;
    
    @SpringBootApplication
    @EnableZuulProxy
    public class MsZuulApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(MsZuulApplication.class, args);
        }
    
        @Bean
        public CorsFilter corsFilter() {
            final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            final CorsConfiguration config = new CorsConfiguration();
            config.setAllowCredentials(true);
            config.addAllowedOrigin("*");
            config.addAllowedHeader("*");
            config.addAllowedMethod("OPTIONS");
            config.addAllowedMethod("HEAD");
            config.addAllowedMethod("GET");
            config.addAllowedMethod("PUT");
            config.addAllowedMethod("POST");
            config.addAllowedMethod("DELETE");
            config.addAllowedMethod("PATCH");
            source.registerCorsConfiguration("/**", config);
            return new CorsFilter(source);
        }
    
    }
    

    Hope this help someone else :)