Most of the machine learning models and deep learning models do prediction through APIs.These APIs must be secured in such a way that no one can use them without your permission. There are many ways to do API authentication but the popular and common one is JWT authentication. In this entire intuition, you will know how to secure your API using Flask and MongoDB. I am assuming that you already have knowledge of Flask and MongoDB. Here is the only implementation part. You will learn the following things
How to register the Users?
Login Flask route for Authentication
Accessing the API route with Generated Tokens.
Steps by Steps to Secure your API
Step 1: Import the necessary Libraries.
import pymongo
from flask import Flask, jsonify, request
from flask_jwt_extended import JWTManager, jwt_required, create_access_token
from pymongo import MongoClient
Pymongo is the official MongoDB Database Python Package. Flask is the Python Web Framework and flask_jwt is the JWT plugin for the Flask Package.
Step 2: Connect to the MongoDB Database Server
Before knowing further keep in mind that MongoDB is a schemaless Database Management System. It is a No SQL database and it differs from other SQL databases. You can do all SQL operations like Create, Read, Update and Delete without creating any Class Model in Python. Use the following code to connect create db and collection for the MongoDB.
# Making a Connection with MongoClient
client = MongoClient("mongodb://localhost:27018/")
# database
db = client["app_database"]
# collection
user = db["User"]
Here, First of all, you will create a client for connection using the MongoClient() method and pass the database URL. I am using the database locally so it is ” mongodb://localhost:27017/“. After that create a database named “app_database“,using client[“app_database”] and then collection “User” using db[“User”].
Step 3: Create a Flask app and Configure it
After making a connection with MongoDB the next step is to create a Flask App and do some configuration on it. Use the Following Code
app = Flask(__name__)
jwt = JWTManager(app)
# JWT Config
app.config["JWT_SECRET_KEY"] = "this-is-secret-key" #change it
As you can see in the above code. First I have created an app and pass it into the JWTManager(app) method to secure the entire Flask Application and also config the JWT_SECRET_KEY.
Step 4: Design your Flask API routes
Now You will design API routes for registering, and log in. Use the following code.
@app.route("/register", methods=["POST"])
def register():
email = request.form["email"]
# test = User.query.filter_by(email=email).first()
test = user.find_one({"email": email})
if test:
return jsonify(message="User Already Exist"), 409
else:
first_name = request.form["first_name"]
last_name = request.form["last_name"]
password = request.form["password"]
user_info = dict(first_name=first_name, last_name=last_name, email=email, password=password)
user.insert_one(user_info)
return jsonify(message="User added sucessfully"), 201
In the registered route first I am checking whether the email is in the database or not and if it is not then Insert the form response to the Database. To find an email in the database You will use the find_one() method and for adding the insert_one() method. After registration, it will return the JSON response with the message User added successfully otherwise returns the User Already Exists.
Login Route
@app.route("/login", methods=["POST"])
def login():
if request.is_json:
email = request.json["email"]
password = request.json["password"]
else:
email = request.form["email"]
password = request.form["password"]
test = user.find_one({"email": email,"password":password})
if test:
access_token = create_access_token(identity=email)
return jsonify(message="Login Succeeded!", access_token=access_token), 201
else:
return jsonify(message="Bad Email or Password"), 401
For the login route, I have created the condition for checking the JSON and form response. Thus it works for both the requests from Json or Form.
Here also I am using the find_one() method for checking username and password. If it is ok then I give the user an Access Token that will be valid for some time to access the Other routes that require access.
Step 5: Secure the Route
Let’s create a route and test and secure it. First, you will create it and then add a decorator below the route
above the function definition. Use the following code.
@app.route("/dashboard")
@jwt_required
def dasboard():
return jsonify(message="Welcome! to the Data Science Learner")
Full Code
import pymongo
from flask import Flask, jsonify, request
from flask_jwt_extended import JWTManager, jwt_required, create_access_token
from pymongo import MongoClient
# Making a Connection with MongoClient
client = MongoClient("mongodb://localhost:27018/")
# database
db = client["app_database"]
# collection
user = db["User"]
app = Flask(__name__)
jwt = JWTManager(app)
# JWT Config
app.config["JWT_SECRET_KEY"] = "this-is-secret-key"
@app.route("/dashboard")
@jwt_required
def dasboard():
return jsonify(message="Welcome! to the Data Science Learner")
@app.route("/register", methods=["POST"])
def register():
email = request.form["email"]
# test = User.query.filter_by(email=email).first()
test = user.find_one({"email": email})
if test:
return jsonify(message="User Already Exist"), 409
else:
first_name = request.form["first_name"]
last_name = request.form["last_name"]
password = request.form["password"]
user_info = dict(first_name=first_name, last_name=last_name, email=email, password=password)
user.insert_one(user_info)
return jsonify(message="User added sucessfully"), 201
@app.route("/login", methods=["POST"])
def login():
if request.is_json:
email = request.json["email"]
password = request.json["password"]
else:
email = request.form["email"]
password = request.form["password"]
test = user.find_one({"email": email, "password": password})
if test:
access_token = create_access_token(identity=email)
return jsonify(message="Login Succeeded!", access_token=access_token), 201
else:
return jsonify(message="Bad Email or Password"), 401
if __name__ == '__main__':
app.run(host="localhost", debug=True)
All tests
Registration
When you press the send button again you will get the error message.
User Details inside the MongoDB database.
Login Testing
Use the token key to get into the dashboard route defined above.
Before Login if you try to access the dashboard URL. Then you will get the following error message.
After Login
Conclusion
Flask is a micro web framework for Python. In addition, you can use it to secure your API for machine learning. This entire intuition covers a basic but effective authentication using username and password. Here you can see that I am storing the password as a simple text. But you can store it as a hashed version in the database. But you have to create an algorithm depending upon your language.
Hope you have understood all the concepts mentioned here. If you have any queries about it then you can contact us or message us at the official Data Science Learner Page.
Other Scenarios
Python Connect to MongoDB with username and password
You can also create a document that contains the username and password for the user. It will allow you to first login to the user with a username and password and the JWT API keys for login sessions. Therefore for a particular time, the user will be logged in, and when the session expires the user will log out and he/she have to login again to access.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.