6.1 User Authentication and Authorization
In this section, we’ll cover how to secure our multi-container app and manage access. This includes user authentication, data encryption, API protection, and setting up secure connections between services.
Goal: Make sure only registered and authenticated users can interact with the app and perform operations.
Implementing JWT (JSON Web Token) for Authentication
Step 1. Install necessary libraries:
pip install Flask-JWT-Extended
Step 2. Set up JWT in a Flask app:
Add these changes to file backend/app/__init__.py
:
from flask_jwt_extended import JWTManager
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://taskuser:taskpassword@database:5432/taskdb'
app.config['JWT_SECRET_KEY'] = 'your_jwt_secret_key' # Replace with your secret key
db = SQLAlchemy(app)
jwt = JWTManager(app)
from app import routes
Step 3. Create routes for registration and authentication:
Add the following routes in the file backend/app/routes.py
:
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from werkzeug.security import generate_password_hash, check_password_hash
from app.models import User, Task
@app.route('/register', methods=['POST'])
def register():
data = request.get_json()
hashed_password = generate_password_hash(data['password'], method='sha256')
new_user = User(username=data['username'], password=hashed_password)
db.session.add(new_user)
db.session.commit()
return jsonify({'message': 'User registered successfully'}), 201
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
user = User.query.filter_by(username=data['username']).first()
if not user or not check_password_hash(user.password, data['password']):
return jsonify({'message': 'Invalid credentials'}), 401
access_token = create_access_token(identity=user.id)
return jsonify({'access_token': access_token}), 200
@app.route('/tasks', methods=['GET'])
@jwt_required()
def get_tasks():
current_user_id = get_jwt_identity()
tasks = Task.query.filter_by(owner_id=current_user_id).all()
return jsonify([task.to_dict() for task in tasks])
Step 4. Update the User model to store passwords:
Update the file backend/app/models.py
:
from app import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
password = db.Column(db.String(120), nullable=False)
tasks = db.relationship('Task', backref='owner', lazy=True)
6.2 Data Encryption
Goal: ensure data protection during transmission between the client and server.
Using HTTPS
Step 1. Setting up Nginx as a reverse proxy with HTTPS support:
Create the nginx.conf
file in the root directory of your project:
server {
listen 80;
server_name your_domain.com;
location / {
proxy_pass http://frontend:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /api {
proxy_pass http://backend:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
Step 2. Creating a Dockerfile for Nginx:
Create a Dockerfile
in the nginx
directory:
FROM nginx:latest
COPY nginx.conf /etc/nginx/nginx.conf
Step 3. Adding Nginx to compose.yaml
:
Update the compose.yaml
file, adding a service for Nginx:
version: '3'
services:
frontend:
build: ./frontend
ports:
- "3000:3000"
networks:
- task-network
backend:
build: ./backend
ports:
- "5000:5000"
depends_on:
- database
networks:
- task-network
environment:
- DATABASE_URL=postgresql://taskuser:taskpassword@database:5432/taskdb
database:
image: postgres:13
environment:
- POSTGRES_DB=taskdb
- POSTGRES_USER=taskuser
- POSTGRES_PASSWORD=taskpassword
networks:
- task-network
volumes:
- db-data:/var/lib/postgresql/data
nginx:
build: ./nginx
ports:
- "80:80"
depends_on:
- frontend
- backend
networks:
- task-network
networks:
task-network:
driver: bridge
volumes:
db-data:
6.3 Getting an SSL Certificate with Let's Encrypt
Step 1. Installing Certbot:
Follow the instructions on the official Certbot website to install Certbot.
Step 2. Getting the certificate:
sudo certbot certonly --standalone -d your_domain.com
Step 3. Configuring Nginx to use SSL:
Update nginx.conf
to use SSL:
server {
listen 80;
server_name your_domain.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name your_domain.com;
ssl_certificate /etc/letsencrypt/live/your_domain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/your_domain.com/privkey.pem;
location / {
proxy_pass http://frontend:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /api {
proxy_pass http://backend:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
Step 4. Updating the Dockerfile for Nginx to copy certificates:
FROM nginx:latest
COPY nginx.conf /etc/nginx/nginx.conf
COPY /etc/letsencrypt /etc/letsencrypt
6.4 API Protection
Goal: restrict access to the API and prevent unauthorized requests.
Using JWT to Protect Routes
We already added protection for task routes using the @jwt_required()
decorator. Make sure all sensitive routes are protected with this decorator:
from flask_jwt_extended import jwt_required, get_jwt_identity
@app.route('/tasks', methods=['GET'])
@jwt_required()
def get_tasks():
current_user_id = get_jwt_identity()
tasks = Task.query.filter_by(owner_id=current_user_id).all()
return jsonify([task.to_dict() for task in tasks])
Restricting Database Access
Goal: prevent unauthorized access to the database.
Setting Up Roles and Privileges
Step 1: Create a User with Limited Privileges
CREATE USER limited_user WITH PASSWORD 'limited_password';
GRANT CONNECT ON DATABASE taskdb TO limited_user;
GRANT USAGE ON SCHEMA public TO limited_user;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO limited_user;
Step 2: Update the DATABASE_URL
Environment Variable:
Update the DATABASE_URL
environment variable in the compose.yaml
file:
environment:
- DATABASE_URL=postgresql://limited_user:limited_password@database:5432/taskdb
GO TO FULL VERSION