Security keeps your web app safe from bad people who want to steal data or cause harm. It protects users and your work.
0
0
Why security is critical in Flask
Introduction
When building a website that stores user passwords or personal info
When your app handles payments or sensitive data
When you want to stop hackers from changing or deleting your data
When you want to make sure only the right people can see certain pages
When you want to keep your app running smoothly without attacks
Syntax
Flask
# Flask security basics example from flask import Flask, request, abort app = Flask(__name__) @app.route('/secret') def secret(): api_key = request.headers.get('API-Key') if api_key != 'mysecretkey': abort(401) # Unauthorized return 'Welcome to the secret page!' if __name__ == '__main__': app.run()
Use abort() to stop requests that are not allowed.
Check headers or user info to control access.
Examples
This example checks a token in the URL to allow access.
Flask
from flask import Flask, request, abort app = Flask(__name__) @app.route('/data') def data(): token = request.args.get('token') if token != 'safe123': abort(403) # Forbidden return 'Here is your data.'
This example uses sessions to keep track of logged-in users.
Flask
from flask import Flask, session, redirect, url_for app = Flask(__name__) app.secret_key = 'supersecret' @app.route('/login') def login(): session['logged_in'] = True return 'Logged in!' @app.route('/dashboard') def dashboard(): if not session.get('logged_in'): return redirect(url_for('login')) return 'Welcome to your dashboard!'
Sample Program
This simple Flask app protects the '/admin' page by checking for a secret API key in the request headers. If the key is wrong or missing, it stops the request with a 401 error. Otherwise, it welcomes the admin.
Flask
from flask import Flask, request, abort app = Flask(__name__) @app.route('/admin') def admin(): api_key = request.headers.get('API-Key') if api_key != 'admin123': abort(401) # Unauthorized return 'Welcome, admin!' if __name__ == '__main__': app.run(debug=True)
OutputSuccess
Important Notes
Always keep your secret keys safe and never share them publicly.
Use HTTPS to protect data sent between users and your app.
Test your security by trying to access protected pages without permission.
Summary
Security protects your app and users from harm.
Check user info or keys to control access.
Use Flask tools like abort() and sessions to help secure routes.