User authentication and authorization in Flask

WBOY
Release: 2023-06-17 18:02:05
Original
2758 people have browsed it

With the widespread use of Web applications, security and data protection have become an important issue in Web application development. To ensure the security of web applications, user authentication and authorization are required. As a popular web development framework, Flask provides many mechanisms for implementing user authentication and authorization.

  1. User Authentication

User authentication refers to using a certain authentication method to determine whether the user's identity is legitimate when the user accesses the Web application. Flask provides many built-in methods to implement user authentication.

1.1. HTTP Basic Authentication

HTTP Basic Authentication is an authentication mechanism based on the HTTP protocol, which requires users to provide user names and passwords for verification when requesting resources. Flask has built-in HTTP basic authentication function, which can be easily implemented through the Flask-BasicAuth extension.

To use the Flask-BasicAuth extension, you need to install and create a BasicAuth object in your Flask application, and then decorate it on the routing function that requires basic authentication. The sample code is as follows:

from flask import Flask from flask_basicauth import BasicAuth app = Flask(__name__) app.config['BASIC_AUTH_USERNAME'] = 'username' app.config['BASIC_AUTH_PASSWORD'] = 'password' basic_auth = BasicAuth(app) @app.route('/') @basic_auth.required def index(): return 'Hello, World!'
Copy after login

In the above code, the two configuration items of BasicAuth are used to set the user name and password. The @basic_auth.required decorator on the routing function implements the basic authentication function.

1.2. Form Authentication

Form authentication is one of the most common authentication methods in web applications. Implementing form authentication in Flask generally requires the use of the Flask-Login extension.

The Flask-Login extension provides a UserMixin class that can be used to represent the user data model. The sample code is as follows:

from flask_login import UserMixin class User(UserMixin): def __init__(self, id, username, password): self.id = id self.username = username self.password = password def get_id(self): return str(self.id)
Copy after login

In the sample code, the User class inherits from the flask_login.UserMixin class, which contains commonly used user authentication methods. In the Flask-Login extension, you also need to provide a user loading function for loading user data. The sample code is as follows:

from flask_login import login_user, LoginManager from flask import Flask, render_template, redirect, url_for from werkzeug.security import generate_password_hash, check_password_hash app = Flask(__name__) app.secret_key = 'your secret key' login_manager = LoginManager(app) # 用户数据 users = { 1: {'username': 'user1', 'password': 'password1'}, 2: {'username': 'user2', 'password': 'password2'}, 3: {'username': 'user3', 'password': 'password3'}, } # 实现用户加载函数 @login_manager.user_loader def load_user(user_id): user = users.get(int(user_id)) if user: return User(user_id, user['username'], user['password']) return None # 实现登录视图 @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] for user_id, user_data in users.items(): if user_data['username'] == username and check_password_hash(user_data['password'], password): user = User(user_id, username, password) login_user(user) return redirect(url_for('index')) return 'Invalid username/password combination' return render_template('login.html') # 实现需要登录才能访问的视图 @app.route('/') @login_required def index(): return 'Hello, World!'
Copy after login

In the sample code, using the Flask-Login extension requires initializing the Flask application and setting secret_key, and then implementing the user loading function through the login_manager.user_loader decorator. Finally, login control can be achieved by using the @login_required decorator on view functions that require login to access.

  1. User authorization

User authorization refers to determining which users can access which resources. Implementing user authorization in Flask requires the use of the Flask-Principal extension.

The Flask-Principal extension provides three classes: Permission, Role, and Identity, which can be used to define user permissions to access resources. Permission represents the permission to request access to a resource, Role represents the user identity or group, and Identity represents the identity information of a user.

The sample code is as follows:

from flask_principal import Principal, Identity, AnonymousIdentity, Permission, RoleNeed app = Flask(__name__) principal = Principal(app) # 定义角色,这里假设有管理员和普通用户两种角色 admin_role = RoleNeed('admin') user_role = RoleNeed('user') # 定义权限 admin_permission = Permission(admin_role) user_permission = Permission(user_role) # 定义 Identity,需要通过 Identity 的认证才能访问需要权限管理的路由 @app.before_request def before_request(): identity = Identity(anonymous=True) if current_user.is_authenticated: identity = Identity(current_user.id) if current_user.is_admin: identity.provides.add(admin_role) else: identity.provides.add(user_role) principal.identity = identity # 在需要受权限控制的路由上使用 requires(permission) 装饰器 @app.route('/admin') @admin_permission.require(http_exception=403) def admin_index(): return 'Hello, Admin!' @app.route('/user') @user_permission.require(http_exception=403) def user_index(): return 'Hello, User!'
Copy after login

In the sample code, two Roles are defined, namely admin_role and user_role. Each Role can define a Permission, which is used to control the permissions required for related operation access. In the before_request function, Identity authentication is implemented, and different Roles are added according to specific circumstances. Permission control can be achieved by using the requires(permission) decorator on routes that require permission management.

Flask provides many methods for implementing user authentication and authorization. Mastering these methods can help developers improve the security of web applications. At the same time, developers also need to carefully consider which method to use to implement user authentication and authorization to ensure application security and user data protection.

The above is the detailed content of User authentication and authorization in Flask. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!