pip install flask flask-sqlalchemy flask-bcrypt flask-jwt-extended
Create a file app.py and add the following setup:
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity
app = Flask(__name__)
# Configure Database and JWT Secret Key
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///users.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["JWT_SECRET_KEY"] = "supersecretkey"
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
jwt = JWTManager(app)
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(200), nullable=False)
def to_dict(self):
return {"id": self.id, "username": self.username}
# Create Database Tables
with app.app_context():
db.create_all()
@app.route("/signup", methods=["POST"])
def signup():
data = request.get_json()
hashed_password = bcrypt.generate_password_hash(data["password"]).decode("utf-8")
new_user = User(username=data["username"], password=hashed_password)
db.session.add(new_user)
db.session.commit()
return jsonify({"message": "User registered successfully"}), 201
Send a POST request with JSON:
{
"username": "john_doe",
"password": "mypassword"
}
Step 5: User Login and JWT Token Generation
@app.route("/login", methods=["POST"])
def login():
data = request.get_json()
user = User.query.filter_by(username=data["username"]).first()
if user and bcrypt.check_password_hash(user.password, data["password"]):
access_token = create_access_token(identity=user.id)
return jsonify({"access_token": access_token})
return jsonify({"error": "Invalid credentials"}), 401
@app.route("/protected", methods=["GET"])
@jwt_required()
def protected():
current_user_id = get_jwt_identity()
user = User.query.get(current_user_id)
return jsonify({"message": f"Hello, {user.username}! You have access to this route."})
Use the JWT token in the Authorization header to access this route:
{
"Authorization": "Bearer your_jwt_token_here"
}
JWTs are stateless, meaning they do not store session data. Instead of actual logout, tokens can be revoked using a blocklist system or by setting short expiration times.
python app.py
In this guide, we implemented:
✅ User authentication (signup & login)
✅ Password hashing using Flask-Bcrypt
✅ JWT-based authentication with Flask-JWT-Extended
✅ Protected routes for authorized access
This setup can be extended with role-based authorization, token expiration management, and refresh tokens for better security. 🚀