K. Siva Prasad Reddy
K. Siva Prasad Reddy

Reputation: 12405

How to integrate a Spring MVC application with Spring Cloud Gateway with OAuth2.0 Security?

I have a Spring Boot MVC + Thymeleaf application which talks to a bunch of microservices via Spring Cloud Gateway.

mvc_app -> gateway -> (service_a, service_b,...)

Now, I want to implement OAuth 2 based security and I want to centralize the authentication process at Gateway level.

That means:

  1. If a user tries access a secured resource on any resource_servers (service_a, service_b, etc) via Gateway, Gateway should redirect the user to IdP Login Page.
  2. After successful authentication, Gateway should use the accessToken to access the secured resource.

This can be achieved as follows:

  1. Make gateway as OAuth 2 client using spring-boot-starter-oauth2-client and appropriate provider/client configuration
  2. Use TokenRelay filter to forward the AccessToken to downstream resource_servers.

The question:

When you are authenticated by Gateway, the authentication state is maintained at Gateway application level. After successful authentication by Gateway, how do you send back the AccessToken, IdToken to mvc_app so that for further requests the same AccessToken will be used?

Upvotes: 1

Views: 834

Answers (1)

ch4mp
ch4mp

Reputation: 12754

You should probably reconsider your intentions: you want to use TokenRelay filter to bridge between a frontend secured with sessions and micro-services secured with tokens (resource servers), but you want to then provide the frontend with the tokens. What's the point?

Your Spring MVC frontend can be a reliable OAuth2 client. You should configure it as an OAuth2 "confidential" client (with oauth2login) and have the gateway be transparent to security (nothing at all there).

Spring REST clients (WebClient, RestTemplate, @FeignClient, even the new RestClient), are all designed to integrate with authorized client repository and transparently populate Authorization header with an access token in session. Refer to the manual of the one you chose for details.

Configuring the Gateway as an OAuth2 client with login and TokenRelay filter is of interest when the frontend is a SPA (Angular, React, Vue, ...) or a native app as it can't be a confidential client. And actually, you don't want to provide such application with the OAuth2 tokens: you have it authorized with just session (and CSRF) cookies and keep token safe on the server.

Upvotes: 5

Related Questions