Enter SPA with OAuth 2
A Spring OAuth 2 secured Application requires:
- Authorization Server: issues tokens for users.
- Resource Server: a secured application that requires users to be authenticated.
- OAuth 2 Client: an application that consumes the resource server. Has access to the token.
This is all you need for an OAuth 2 application. Except, what if the client is an SPA? like Nidam with React. Should the token be saved by the React application and for every call it gets included in the request? That's NOT secure, it's called a public client which is not recommended.
Instead, what security experts recommend is the use of what's called BFF (Backend For Frontend). Read this and this.
What BFF does is:
- Set between the resource server and SPA client.
- After successful login by a user using the SPA. The authorization server sends back the token to the BFF.
- The BFF then saves the token and associates it with a
SESSION
cookie. - The BFF then redirects back to the frontend with the
SESSION
cookie set. - Now the frontend is authenticated.
- Every frontend request is sent to the BFF, not the resource server. With the aforementioned cookie automatically set.
- The BFF then calls the resource server with the Token correspondent to the Session Cookie.
- The response is returned to the BFF which in turn returns it to the frontend.
The Token is saved securely in the backend. The BFF in this case is called a confidential client.
Credit
All credit for the BFF and Server Proxy implemented in Nidam goes to Jérôme Wacongne and his article in baeldung.com OAuth2 Backend for Frontend With Spring Cloud Gateway. The BFF and Reverse Proxy in Nidam is pretty much a copy paste from his article. I strongly recommend to go there and read his article.