Introduction to Securing a Microservice in a Rails Application
This tutorial will create a plan for implementing authentication into a Ruby on Rails application.
Guide Tasks
  • Read Tutorial

Now that we have a functional microservice we need to secure it so that it can only be accessed by authorized outside applications. If we were building an API that was going to be used by the world, such as Twitter or Google Maps, we would need to build a full API dashboard, key generator, etc. However microservices are simply a feature inside of a larger application architecture.

For this reason we only need to ensure that we're blocking hackers from communicating with our system. So let's organize our thoughts on what we need to do. I always like to start with a plan since that helps me decide on what types of tests to write.

Requirements for authentication

  • We need to have a model that manages the authorized applications
  • The model will store a unique API key, the app name, and connect to the Notification model
  • Each time the microservice receives a request it needs to verify the application prior to sending the notification

Strategy

Now that we know what we need to implement authorization, let's discuss some of the steps we'll take to build the feature.

  1. Obviously we'll start with building tests that match the requirements, we'll create a new spec file for a Client model.
  2. We'll create an ActiveRecord model called Client that will have the attributes source_app and api_key.
  3. In the notification workflow we'll build in the requirement that a API request will need to contain a matching API key.
  4. We'll implement a validation to ensure that the api_key value is unique.
  5. Lastly we'll implement a key generator to securely create API keys that we can give to outside applications, we'll use the command SecureRandom.base64.tr('+/=', 'Qrt') to generate the key.

Now that we have a plan, in our next guide we'll build out our initial specs and implementation.