How to Authenticate and Redirect in Decoupled Front-End Web Applications

authenticationbackendfront-endweb-applications

I have a coupled web application (frontend and api backend served from the same application). It's worked well for our needs but I've been curious about the differences that would go into having a completely decoupled front and backend.

I'm specifically wondering about how handling authentication requests would work with this approach. Right now I have the option of redirecting a request do a different page, i.e. hitting the /dashboard page would redirect you to /login if the token in a cookie doesn't authenticate.

How would that be handled without all request running through a single application?

I'm assuming I'd create a reverse proxy to pass along any requests from the /api path to the backend server. But everything else would be handled by whatever serves the frontend. If I'm thinking about this correctly would each request for a page on the frontend be "unrestricted" in a sense and then after requesting authentication information from the backend handle redirecting to the correct page.

Going back to the /dashboard to /login example, would it follow this flow?

  • Users requests /dashboard url
  • NGINX serves the static resources needed for the dashboard SPA.
  • Frontend JavaScript code requests auth info from a backend endpoint
  • If the user's cookie doesn't authenticate, redirect the user to /login through JavaScript.

Am I on the right track or is there a better way to solve this problem?

Best Answer

You would handle it much the same as you do now. Decoupling the Api doesn't mean you have zero server side code on your website.

Specifically you want to be able to deny unauthenticated users access to your javascript, images, html and other content.

You can do this by keeping your current server side authentication code to handle the login and token generation. Once the login has succeeded the token can be read by the javascript and subsequently used to auth requests to the API as well as being passed to the Webserver to authenticate page requests

Related Topic