Nasajon Flask Authentication

0.11.1 · active · verified Fri Apr 17

nsj-flask-auth is a basic module designed for authenticating Flask applications within the Nasajon ecosystem. It provides tools for JWT-based authentication, integrating with Flask routes via decorators. Currently at version 0.11.1, its release cadence is tied to internal Nasajon project needs, typically with updates released as new features or fixes are required.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `nsj-flask-auth` with a Flask application, configure essential settings like the JWT secret and token header, and protect a route using the `@auth_required` decorator. Configuration is pulled from `app.config`, which can be populated via environment variables for security and flexibility. Run this, then access `/protected` with a valid JWT in the Authorization header to test.

import os
from flask import Flask, jsonify
from nsj_flask_auth.auth_manager import AuthManager
from nsj_flask_auth.decorator import auth_required

app = Flask(__name__)

# Configure authentication settings
app.config['NSJ_AUTH_TOKEN_HEADER'] = os.environ.get('NSJ_AUTH_TOKEN_HEADER', 'Authorization')
app.config['NSJ_AUTH_JWT_SECRET'] = os.environ.get('NSJ_AUTH_JWT_SECRET', 'your-super-secret-key-here')
app.config['NSJ_AUTH_ALGORITHMS'] = os.environ.get('NSJ_AUTH_ALGORITHMS', 'HS256') # Comma-separated for multiple

# Initialize AuthManager with the Flask app
auth_manager = AuthManager(app)

@app.route('/')
def home():
    return "Welcome! This route is public."

@app.route('/protected')
@auth_required
def protected_route():
    # Access current user info after authentication
    user_info = auth_manager.current_user()
    return jsonify({"message": "This is a protected route!", "user": user_info.to_dict()})

if __name__ == '__main__':
    # Example usage: Set environment variables or ensure app.config is properly set
    # For testing, you might use a tool like Postman to send a JWT token
    # in the 'Authorization' header: 'Bearer <your_jwt_token>'
    app.run(debug=True, port=5000)

view raw JSON →