Authorization and Authentication in Flask
In Flask, authorization and authentication can be implemented using various libraries and techniques. Here are some common approaches:
Authorization and authentication in Flask are important for access control and user identity verification. Extensions like Flask-Login, Flask-Security, or Flask-Principal are used to integrate these systems with Flask.
User Model:
from werkzeug.security import generate_password_hash, check_password_hash
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
password_hash = db.Column(db.String(120))
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
from flask_login import LoginManager, login_user, logout_user, login_required
login_manager = LoginManager()
login_manager.init_app(app)
@app.route('/login', methods=['GET', 'POST'])
def login():
# Code to verify the user credentials and log the user in
user = User.query.filter_by(username=form.username.data).first()
if user is not None and user.check_password(form.password.data):
login_user(user)
return redirect(url_for('index'))
from flask_login import current_user
from functools import wraps
def role_required(role):
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if not current_user.role == role:
return abort(401) # Unauthorized
return fn(*args, **kwargs)
return wrapper
return decorator
@app.route('/admin')
@role_required('admin')
def admin_page():
return render_template('admin.html')