Search code examples
springauthenticationmicroservices

Spring Gateway and Authentication routes


I have a simple Spring Gateway project that uses 3 microservices - 1 service for doing authentication and 2 "secured" microservices (i.e. all requests to these services must be authenticated).

The authentication service which is responsible for authentication (generate JWT tokens) works fine via the Gateway.

As in I can access it via the Gateway to create tokens and via the Gateway to confirm if a token is valid.

In my scenario when the user attempts to access a “secure” microservice I want

  1. Call the auth service to verify the user has the correct JWT token
  2. If the use does not have the required permission confirmed in (a) return some Http status 404 code with a specific message If the user is authenticated confirmed by (a) allow the call to proceed to request route

Reading around seems to suggest I would need to apply some filter on the Spring Gateway routes to do this.

The examples on https://cloud.spring.io/spring-cloud-gateway/multi/multi__developer_guide.html#_writing_custom_gatewayfilter_factories aren’t too clear on how to achieve this. Wondering is this the reccomended approach?

If so can someone point me in the direction of what this would look like in terms of the routing code in Spring Gateway

 builder.routes()
            .route(route -> route.path("/auth/**")                     
                        .uri(LOAD_BALANCED_AUTHENTICATION_SERVICE)
                        .id("authentication-service"))
                .route(route -> route.path("/images/**")
                        .filters(SOME_AUTHENTICATION_FILTER)
                        .uri(LOAD_BALANCED_IMAGES_SERVICE)
                        .id("images-service"))
                .route(route -> route.path("/inbox/**")
                        .filters(SOME_AUTHENTICATION_FILTER)
                        .uri(LOAD_BALANCED_INBOX_SERVICE)
                        .id("inbox-service"))
 .build();

Note I haven't implemented the filter (SOME_AUTHENTICATION_FILTER) shown above yet as I'm not clear from the examples how to call the authentication service from the filter. Also unclear from the examples how the filters would terminate a request or allow the request to proceed.


Solution

  • As I understand, you have two questions, first one the routing recommended flow; and as you defined exactly will be good, if the filter worked correctly move route to Service X.

    For the other part, How to define the custom filter? you need to do the authorization check inside it using your secure service; there is a good example which can tell you how to handle this, and how to terminate the request also with descriptive messages.

    You can find it here Spring Cloud Gateway Custom Filter