Using Zuul as an authentication gateway

前端 未结 3 1508
轻奢々
轻奢々 2020-12-07 14:30

Background

I want to implement the design presented in this article.

It can be summarised by the diagram below:

  1. The client fi
3条回答
  •  醉酒成梦
    2020-12-07 15:09

    I know I am very late to answer You can approach with prefilter of zuul. The steps you have to follow is given below.

     //1. create filter with type pre
     //2. Set the order of filter to greater than 5 because we need to run our filter after preDecoration filter of zuul.
     @Component
     public class CustomPreZuulFilter extends ZuulFilter {
    
      private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Override
    public Object run() {
        final RequestContext requestContext = RequestContext.getCurrentContext();
        logger.info("in zuul filter " + requestContext.getRequest().getRequestURI());
        byte[] encoded;
        try {
            encoded = Base64.encode("fooClientIdPassword:secret".getBytes("UTF-8"));
            requestContext.addZuulRequestHeader("Authorization", "Basic " + new String(encoded));
    
            final HttpServletRequest req = requestContext.getRequest();
            if (requestContext.getRequest().getHeader("Authorization") == null
                    && !req.getContextPath().contains("login")) {
                requestContext.unset();
                requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
    
            } else {
                  //next logic
                }
            }
    
        } catch (final UnsupportedEncodingException e) {
            logger.error("Error occured in pre filter", e);
        }
    
        return null;
    }
    
    
    
    @Override
    public boolean shouldFilter() {
        return true;
    }
    
    @Override
    public int filterOrder() {
        return 6;
    }
    
    @Override
    public String filterType() {
        return "pre";
    }
    
    }
    

    requestContext.unset() will Resets the RequestContext for the current threads active request. and you can provide a response status code.

提交回复
热议问题