Search code examples
netflix-zuulspring-cloud-netflix

ZUUL send basic authentication to downstream application


I have a spring boot microservice which requires basic authentication data ie fixed userid/password (like admin/password). I am using Spring cloud netflix ecosystem to orchestrate microservices. Zuul is my API gateway.

My question how to send basic authentication details to my application from Zuul so that when accessed via Zuul it won't ask for userid/password.


Solution

  • You can add a custom filter and add the Authorization header to the request.
    The Authorization header is simply base64 encoded "username:password" string.

    public class AuthenticatedFilter extends ZuulFilter {
    
      @Override
      public String filterType() {
        return "pre";
      }
    
      @Override
      public int filterOrder() {
        return 10;
      }
    
      @Override
      public boolean shouldFilter() {
        return true;
      }
    
      @Override
      public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        String auth = "username" + ":" + "password";
        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1")));
        String authValue = "Basic " + new String(encodedAuth);
        ctx.addZuulRequestHeader(HttpHeaders.AUTHORIZATION, authValue);        
        return null;
      }
    }
    

    EDIT: You'll also need to create the bean for this filter for Zuul to pick it up. So in your Configuration class/Main application class, add:

    @Bean
    public AuthenticatedFilter getAuthenticatedFilter () {
        return new AuthenticatedFilter();
    }