Backend Development
Python Tutorial
Flask-RESTful and Flask-JWT: User authentication and authorization in Python web applicationsFlask-RESTful and Flask-JWT: User authentication and authorization in Python web applications
In modern web applications, user authentication and authorization are very critical security measures. With the popularity and usage of Python, Flask-RESTful and Flask-JWT have become the preferred solutions for user authentication and authorization in Python web applications. This article will introduce in detail the use of Flask-RESTful and Flask-JWT, and how to implement user authentication and authorization in Python web applications.
Introduction to Flask-RESTful
Flask-RESTful is an extension library of Flask that can help quickly build RESTful API interfaces. It provides many useful functions, such as input validation, request parsing, etc. With Flask-RESTful, we can easily build a simple Web API. Here is a simple example:
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
def get(self):
return {'hello': 'world'}
api.add_resource(HelloWorld, '/')
if __name__ == '__main__':
app.run(debug=True) In this example, we create a resource named HelloWorld and add it to api in the object. Finally, we can access the HelloWorld resource through the / route. When we access the / route, call the get method of the HelloWorld resource and return a JSON response {'hello': 'world'}.
Introduction to Flask-JWT
Flask-JWT is another extension library for Flask for implementing JSON Web Token (JWT) authentication in web applications. JWT is an open standard for securely transmitting information between users and servers. It is based on JSON and usually consists of three parts, namely header, payload and signature. The header contains the JWT type and algorithm information used, the payload contains the data information that needs to be transmitted, and the signature is used to verify whether the data is correct. Flask-JWT simplifies the generation and verification of JWT, making it easier to implement user authentication in web applications. Here is a simple example:
from flask import Flask
from flask_jwt import JWT, jwt_required, current_identity
from werkzeug.security import safe_str_cmp
app = Flask(__name__)
app.config['SECRET_KEY'] = 'super-secret'
class User(object):
def __init__(self, id, username, password):
self.id = id
self.username = username
self.password = password
def __str__(self):
return f"User(id='{self.id}', username='{self.username}')"
users = [
User(1, 'user1', 'password'),
User(2, 'user2', 'password')
]
username_table = {u.username: u for u in users}
userid_table = {u.id: u for u in users}
def authenticate(username, password):
user = username_table.get(username, None)
if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')):
return user
def identity(payload):
user_id = payload['identity']
return userid_table.get(user_id, None)
jwt = JWT(app, authenticate, identity)
@app.route('/protected')
@jwt_required()
def protected():
return {'hello': current_identity.username}
if __name__ == '__main__':
app.run(debug=True)In this example, we first define a User class to store the user's authentication information. In the authenticate function, enter a username and password, and the function will return a user object. In the identity function, enter a jwt payload, and the function will return a user object based on the user id in the jwt. By calling the JWT constructor, we add a custom authentication method and a custom user identification method to the application. Finally, the @jwt_required decorator is used in the protected route's decorator to ensure that only authenticated users can access protected resources.
The combination of Flask-RESTful and Flask-JWT
We can use Flask-RESTful and Flask-JWT together to implement a complete web application, including user authentication and authorization mechanisms. The following is a simple example:
from flask import Flask
from flask_restful import Resource, Api, reqparse
from flask_jwt import JWT, jwt_required, current_identity
from werkzeug.security import safe_str_cmp
app = Flask(__name__)
app.config['SECRET_KEY'] = 'super-secret'
api = Api(app)
class User(object):
def __init__(self, id, username, password):
self.id = id
self.username = username
self.password = password
def __str__(self):
return f"User(id='{self.id}', username='{self.username}')"
users = [
User(1, 'user1', 'password'),
User(2, 'user2', 'password')
]
username_table = {u.username: u for u in users}
userid_table = {u.id: u for u in users}
def authenticate(username, password):
user = username_table.get(username, None)
if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')):
return user
def identity(payload):
user_id = payload['identity']
return userid_table.get(user_id, None)
jwt = JWT(app, authenticate, identity)
class HelloWorld(Resource):
def get(self):
return {'hello': 'world'}
class Secret(Resource):
@jwt_required()
def get(self):
return {'secret': 'resource', 'user': current_identity.username}
class Login(Resource):
def post(self):
parser = reqparse.RequestParser()
parser.add_argument('username', type=str, help='Username cannot be blank', required=True)
parser.add_argument('password', type=str, help='Password cannot be blank', required=True)
args = parser.parse_args()
user = authenticate(args['username'], args['password'])
if user:
return {'access_token': jwt.jwt_encode_callback({'identity': user.id})}
else:
return {'message': 'Invalid username or password'}, 401
api.add_resource(HelloWorld, '/')
api.add_resource(Secret, '/secret')
api.add_resource(Login, '/login')
if __name__ == '__main__':
app.run(debug=True) In this example, in addition to defining the HelloWorld resource, we also define the Secret resource and Loginresource. In the Secret resource, pass the @jwt_required decorator to ensure that only authenticated users have access. In the Login resource, we parse the POST request and use the authenticate function to verify the user's identity information. If the verification is successful, the JWT token is returned, otherwise a 401 status code is returned. Finally, we added all the resources to the api object and started the web application using Flask's run method.
Summary
In Python web application development, Flask-RESTful and Flask-JWT are very useful extension libraries. Through them, we can easily build and secure Web APIs and add user authentication and authorization mechanisms to web applications. Using Flask-RESTful and Flask-JWT can reduce our development time and development costs, making it easier for us to implement the functions of web applications.
The above is the detailed content of Flask-RESTful and Flask-JWT: User authentication and authorization in Python web applications. For more information, please follow other related articles on the PHP Chinese website!
Python: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AMPython excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.
Python and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AMTo maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.
Python: Games, GUIs, and MoreApr 13, 2025 am 12:14 AMPython excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.
Python vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AMPython is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.
The 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AMYou can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.
Python: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AMPython is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.
How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PMYou can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.
How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AMHow to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version
Useful JavaScript development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft





