How do you protect your backend API in your microservice if you use a Single Page Application on the frontend?

djviolin

István Lantos

Posted on March 19, 2018

How do you protect your backend API in your microservice if you use a Single Page Application on the frontend?

I currently working on a pet project where I intend to learn a "simple" microservice architecture, meaning no universal rendering (or I thought it would be simple).

I have a backend REST API written in Go, which is proxying a third-party API. Later on it will be replaced with a Postgres database. Right now serving content under 127.0.0.1:8080/api/v1.

I have a static fileserver written in Go for SPA, which is serving a Single Page Application written in Vue.js, generated by vue-cli. This fileserver serving content under 127.0.0.1:8081. This vue app querying data from the API server with axios, fecthing AJAX requests.

This is where I hit the first problem: if I not whitelisting the address of the static fileserver on the API server, so the server doesn't have any CORS header presented, like:

Access-Control-Allow-Origin: http://127.0.0.1:8081
# or
Access-Control-Allow-Origin: *
Enter fullscreen mode Exit fullscreen mode

The request got ignored by the browser.


Another problem (well, not really a problem) that I had to drop the relative urls in axios (because they are not on the same server anymore), meaning replacing:

return this.$http.get(`/api/v1/${this.id}/`, {
Enter fullscreen mode Exit fullscreen mode

with:

return this.$http.get(`//127.0.0.1:8080/api/v1/${this.id}/`, {
Enter fullscreen mode Exit fullscreen mode

in the vue app.

Am I doing something wrong here? How should I make request to the API server from the SPA from another server?


How can I protect my backend API from people to using it without restrictions?

I guess I have to implement a rate limiter for sure. I plan to use HAProxy for load balancing and probably this is the point where it should limit the requests from users who wants to execute DDOS attacks or use the database as a free fountain for their sites.

But there are no other way of limiting the API accessing it from the browser bar, if they type in the address of the API server? What about GraphQL? Same situation?


This site will not feature any authentication, user management, or restricted access at the start. But if I try to implement such feature in the future, how can I implement user authentication safely, not shooting myself in the leg? What are the best practices to do this, if I completely want to ditch server-side or universal rendering?

I want to have an SPA and an API server which will be a good start for web and mobile apps, too.

💖 💪 🙅 🚩
djviolin
István Lantos

Posted on March 19, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related