Search code examples
spring-mvcspring-bootmicroservicesnetflix-eurekanetflix-zuul

Authentication to access Spring boot Zuul Service routes


I have configured my micro services using Spring boot zuul and eureka services. Now I need to authenticate all routes/REST API calls. I mean, for all APIs client send one accessToken. On zuul service, before routing to the particular service, I have to call a micro service (auth-service) with accessToken and that auth-service will check the user exists or not for the accessToken sent. If the accessToken is valid then only routing should happen.

Please help me to implement this using spring boot service.

Thanks.


Solution

  • You need to write a filter. A zuul pre filter is what you need. You can access your auth server within the filter and if the token is invalid you don't call your microservice and return a response immediately. If it is valid you let the request go down to micro services.

    An example filter class:

    public class AuthFilter extends ZuulFilter {
    
        @Autowired
        RestTemplate restTemplate;
    
        @Override
        public String filterType() {
            return "pre";
        }
    
        @Override
        public int filterOrder() {
            return 1;
        }
    
        @Override
        public boolean shouldFilter() {
            return true;
        }
    
        @Override
        public Object run() {
            RequestContext ctx = RequestContext.getCurrentContext();
            //get your token from request context and send it to auth service via rest template
            boolean validToken = restTemplate.exchange(or getForObject or other methods of restTemplate which you find suitable for method and return type of your auth service controller method)
            if(!validToken) {
                ctx.setSendZuulResponse(false); //This makes request not forwarding to micro services
                ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
                ValidationResponse validationResponse = new ValidationResponse();
                validationResponse.setSuccess(false);
                validationResponse.setMessage("Invalid Access...");
                ObjectMapper mapper = new ObjectMapper();
                String responseBody = mapper.writeValueAsString(validationResponse);
                ctx.setResponseBody(validationResponse);
                ctx.getResponse().setContentType("application/json");
                //If you want to do any thing else like logging etc, you can do it.
            }
            return null;
        }
    
    }