springoauth-2.0spring-cloud-gateway

Spring Gateway and OAuth


I need to configure a Spring Gateway to use OAuth.

My use case is as follows:

An external provider exposes an API to us, which needs OAuth2 token. Currently, every consumer within out network uses a WebCllient with OAuth2 integration to perform the authentication, however, we've been asked to modify it.

They asked us to put a Spring Gateway in the middle and make it perform the OAuth. That Spring Gateway must automatically perform OAuth login when needed and automatically inject the required headers in the request, exposed an unsecure endpoint for LAN clients to consume.

Later on that gateway will rely in OUR security instead of the providers security, but that's not the point of this question, for simplification, just assume we want to expose unsecured endpoints.

At this point, I'm about to write a GlobalFilter for the gateway myself.


Solution

  • To "login" a user with OAuth2 authorization_code flow on spring-cloud-gateway, you do just as usual in Spring Boot apps: use spring-boot-starter-ouath2-client and provide a SecurityFilterChain bean with oauth2Login.

    To switch from session security to Bearer authorization when going through spring-cloud-gateway, you use the TokenRelay filter (this will replace the session cookie with an Authorization header containing the access token in session). The downstream services are then configured as stateless OAuth2 resource servers.

    I wrote an article about that on Baeldung