Rails 5 API gateway template to handle the multi-tenant authentication and authorization from the external callers to the microservice level using JSON Web Tokens (JWT).
JWT authentication was implemented from scratch. For a better solution check the knock gem.
Subdomains and multitenancy were implemented from scratch. For a better solution check the apartment gem
The API Gateway is the entry point to all the services that your application is providing. It's responsible for service discovery (from the client side), routing the requests coming from external callers to the right microservices. Whenever the user wants to access a certain resource, he'll request it from the API Gateway and will send the JWT along with his request. The API Gateway will forward the request with the JWT to the microservice that owns this resource. The microservice will then decide to either grant the user the resource (if the user has the required permissions) or not. Based on the implementation, the microservice can make this decision by itself (if it knows the permissions of this user over this resource) or simply forward the request to one of the Authorization Servers within the environment to determine the user's permissions.
To illustrate further, a user starts by sending his credentials to the API gateway which will forward the credentials to the Authorization Server (AS). The AS will generate a JSON Web Token (JWT) and will return it back to the user.
This example app can be run with Docker and Docker Compose. To support this, you must have Docker installed and running locally. You may also require that the Docker daemon supports connections on the default Unix socket /var/run/docker.sock
On macOS, I recommend using Docker for Mac.
Add your application configuration to your .env file in the root of your project:
API_GATEWAY_DBThe database name
API_GATEWAY_DB_ROLEDatabase role
API_GATEWAY_DB_PASSWORDThe password for the user set in the API_GATEWAY_DB_ROLE environment variable
API_GATEWAY_SECRET_KEY_BASEThe application secret key value found in config/secrets.yml. Rails provides rake secret for just this purpose.
API_GATEWAY_DB_HOSTThe PostgreSQL server listening port
API_GATEWAY_DB_PORTThe PostgreSQL database port
Run the containers
docker-compose upCreate the database
docker-compose run app rake db:createRun migrations
docker-compose run app rake db:migrate