Search code examples
spring-cloudmicroservicesoauth-2.0netflix-zuulwso2-identity-server

Get AccessToken from spring cloud zuul API Gateway


We are using zuul as API gateway in spring cloud. Now we want to extract access token from zuul for further implementation.Please provide suggestion how we want to implement. Thank you


Solution

  • To read the authorization header you will need to create a filter in ZUUL my thought is you will need a pre filter you can change it based on your need. Here is what you will need.

    public class TestFilter extends ZuulFilter {
    
    @Override
    public boolean shouldFilter() {
    
        return true;
    }
    
    @Override
    public Object run() {
    
        final RequestContext ctx = RequestContext.getCurrentContext();
        final HttpServletRequest request = ctx.getRequest();
     //Here is the authorization header being read.
        final String xAuth = request.getHeader("Authorization");
     //Use the below method to add anything to the request header to read downstream. if needed.
        ctx.addZuulRequestHeader("abc", "abc"); 
    
        return null;
    }
    
    @Override
    public String filterType() {
    
        return "pre";
    }
    
    @Override
    public int filterOrder() {
    
        return 1;
    }
    
    }
    

    You will need a @Bean declaration for Filter in the class where you have @EnableZuulProxy

    @Bean
    public TestFilter testFilter() {
        return new TestFilter();
    }
    

    Hope this helps.!!!