Sobes.tech
Junior — Middle

How did you organize request security in your project, and what measures did you use to ensure safety?

sobes.tech AI

Answer from AI

The following measures are commonly used to protect requests in Python projects:

  • Authentication and Authorization: Using tokens (JWT, OAuth), sessions, or API keys to verify access rights.
  • Validation and sanitization of input data: To prevent SQL injections, XSS, and other attacks.
  • Using HTTPS: To encrypt traffic between the client and server.
  • Rate limiting: To protect against DDoS and brute force attacks.
  • CSRF protection: In web applications to prevent cross-site request forgery.
  • Logging and monitoring: To detect suspicious activity.

An example of using Flask with JWT to protect an endpoint:

from flask import Flask, request, jsonify
from flask_jwt_extended import JWTManager, jwt_required, create_access_token

app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'super-secret'
jwt = JWTManager(app)

@app.route('/login', methods=['POST'])
def login():
    username = request.json.get('username')
    password = request.json.get('password')
    # User verification
    if username == 'user' and password == 'pass':
        access_token = create_access_token(identity=username)
        return jsonify(access_token=access_token)
    return jsonify({'msg': 'Bad credentials'}), 401

@app.route('/protected', methods=['GET'])
@jwt_required()
def protected():
    return jsonify({'msg': 'Access granted'})

if __name__ == '__main__':
    app.run(ssl_context='adhoc')  # Running with HTTPS

This approach provides basic protection for requests and data.