Building Python Microservices, Part III — Security
Here is a link to the previous parts :
So far, the system consists of a CouchDB database, a python API using connexion and documented with Swagger docs.
All routes thus far are open to the public and anyone who knows the IP can access the routes. This should be fixed by setting up some basic security.
There are a number of ways to handle security :
- Basic Auth
- API Key
In this post, basic auth will be used however if you have experience with oauth and connexion, please submit a PR to demonstrate this example too.
About Basic Auth:
If you choose to use Basic Auth in a production enviroment you must use HTTPS.
Deleting a product securely :
Deleting is a very important operation. It must be secured so only those with access can delete an item from the DB.
There are three main steps in performing the operation:
- Check if the requestor has supplied a valid auth header
- Validate the credential provided using a on server variable — this is optional however in doing so we prevent connecting to the db with invalid credential
- Attempt the connection to the DB using the details
The update function is similar to our create and read. First the product is queried in the db, if it is found one way would be to reassign the values of the result and save the result.
A better way would be to assign the needed ‘_rev’ property of the found product to our query product and overwrite the data.
Our last 2 jobs are to refactor the create_product function to also implement the same security checks. The read_product function is optional, leaving it open allows anyone to query whats in the database.
The security setup now means that all requests with an Authorisation Header will be rejected and the provided password will be checked before establishing a connection to the database.
All the code for this post can be found on this github repo :
The branch part-3 contains the relevant code for this page.
Here is a link to other parts :