CodeGym /Corsi /Docker SELF /Sicurezza e gestione degli accessi

Sicurezza e gestione degli accessi

Docker SELF
Livello 24 , Lezione 0
Disponibile

6.1 Autenticazione e autorizzazione degli utenti

In questa fase vedremo come garantire la sicurezza della nostra applicazione multi-container e la gestione degli accessi. Questo include l'autenticazione degli utenti, la crittografia dei dati, la protezione delle API e la configurazione di connessioni sicure tra i servizi.

Obiettivo: garantire che solo gli utenti registrati e autenticati possano interagire con l'applicazione ed eseguire operazioni.

Implementazione di JWT (JSON Web Token) per l'autenticazione

Passo 1. Installazione delle librerie necessarie:

Terminal

pip install Flask-JWT-Extended

Passo 2. Configurazione di JWT nell'app Flask:

Aggiungi le seguenti modifiche al file backend/app/__init__.py:

Python

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'  # Sostituisci con la tua chiave segreta
db = SQLAlchemy(app)
jwt = JWTManager(app)
        
from app import routes    

Passo 3. Creazione dei percorsi per registrazione e autorizzazione:

Aggiungi i seguenti percorsi al file backend/app/routes.py:

Python

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': 'Utente registrato con successo'}), 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': 'Credenziali non valide'}), 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])

Passo 4. Aggiornamento del modello User per memorizzare le password:

Aggiorna il file backend/app/models.py:

Python

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 Crittografia dei dati

Obiettivo: garantire la protezione dei dati durante il trasferimento tra il client e il server.

Utilizzo di HTTPS

Passo 1. Configurare Nginx come reverse proxy con supporto HTTPS:

Crea il file nginx.conf nella directory radice del progetto:

Testo

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;
    }
}

Passo 2. Creare un Dockerfile per Nginx:

Crea il file Dockerfile nella directory nginx:

dockerfile

FROM nginx:latest
COPY nginx.conf /etc/nginx/nginx.conf

Passo 3. Aggiungere Nginx a compose.yaml:

Aggiorna il file compose.yaml aggiungendo un servizio per Nginx:

Yaml

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 Ottenere un certificato SSL con Let's Encrypt

Passo 1. Installazione di Certbot:

Segui le istruzioni sul sito ufficiale di Certbot per installare Certbot.

Passo 2. Ottenere il certificato:

Terminal

sudo certbot certonly --standalone -d your_domain.com

Passo 3. Configurare Nginx per utilizzare SSL:

Aggiorna nginx.conf per utilizzare SSL:

Text

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;
    }
}

Passo 4. Aggiornare Dockerfile per Nginx per copiare i certificati:

dockerfile

FROM nginx:latest
COPY nginx.conf /etc/nginx/nginx.conf
COPY /etc/letsencrypt /etc/letsencrypt

6.4 Protezione dell'API

Obiettivo: limitare l'accesso all'API e prevenire richieste non autorizzate.

Utilizzo di JWT per proteggere i percorsi

Abbiamo già aggiunto la protezione per i percorsi delle attività, utilizzando il decoratore @jwt_required(). Assicurati che tutti i percorsi sensibili siano protetti da questo decoratore:

Python

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])

Limitazione dell'accesso al database

Obiettivo: prevenire l'accesso non autorizzato al database.

Configurazione di ruoli e privilegi

Passo 1. Creazione di un utente con privilegi limitati:

SQL

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;

Passo 2. Aggiornamento della variabile di ambiente DATABASE_URL:

Aggiorna la variabile di ambiente DATABASE_URL nel file compose.yaml:

Yaml

environment:
  - DATABASE_URL=postgresql://limited_user:limited_password@database:5432/taskdb
Commenti
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION