Flask-Security: Adding user authentication and password encryption to Python web applications

WBOY
Release: 2023-06-17 14:28:40
Original
2420 people have browsed it

Flask-Security: Adding user authentication and password encryption to Python web applications

As the Internet continues to develop, more and more applications require user authentication and password encryption to protect users Data security. In the Python language, there is a very popular web framework-Flask. Flask-Security is an extension library based on the Flask framework that helps developers easily add user authentication and password encryption capabilities to Python web applications.

Flask-Security has the following features:

  • Can be easily integrated into existing Flask applications
  • Supports multiple authentication methods, including passwords , tokens, social media login, etc.
  • Supports password encryption and decryption (using Bcrypt encryption algorithm)
  • Provides user role management functions, which can assign different roles to different users to Controlling user access to your application

In this article, we'll cover how to use Flask-Security to add user authentication and password encryption capabilities to your Python web application.

Installing Flask-Security

Before we start using Flask-Security, we need to install it first. We can use pip to install Flask-Security:

pip install Flask-Security
Copy after login

Of course, we also need to install some other necessary dependent libraries, including Flask and Flask-SQLAlchemy (or other ORM libraries):

pip install Flask Flask-SQLAlchemy
Copy after login

Configuring Flask-Security

After installing Flask-Security, we need to configure some parameters to enable user authentication and password encryption. First, we need to introduce the Flask-Security extension library into the Flask application:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin, login_required
Copy after login

Next, we need to define some necessary configuration parameters, including database connection information, keys, etc.:

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
app.config['SECRET_KEY'] = 'mysecretkey'
Copy after login

Here we use SQLite as our database and save it in a file. Of course, you can also use other databases (such as MySQL or PostgreSQL), just modify the corresponding database connection information.

Next, we need to define a User and a Role class. Here we use SQLAlchemy as the ORM library:

db = SQLAlchemy(app)


class Role(db.Model, RoleMixin):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)
    description = db.Column(db.String(255))


class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))
    active = db.Column(db.Boolean())
    confirmed_at = db.Column(db.DateTime())
    roles = db.relationship('Role', secondary='user_roles',
                             backref=db.backref('users', lazy='dynamic'))


user_datastore = SQLAlchemyUserDatastore(db, User, Role)


class UserRoles(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    user_id = db.Column(db.Integer(), db.ForeignKey('user.id'))
    role_id = db.Column(db.Integer(), db.ForeignKey('role.id'))
Copy after login

Here, we define a User class and a Role class, and add They are associated with the user_roles table respectively. We also define a user_datastore object for managing user and role information.

Next, we need to configure the parameters and classes we defined through the Security extension library:

security = Security(app, user_datastore)
Copy after login

At this point, we have completed the configuration of Flask-Security. Next, we can use user authentication and password encryption features in our Flask application.

Using Flask-Security for user authentication and password encryption

Before using Flask-Security, we need to create a new Flask blueprint and define some view functions in it to handle users Login, registration, logout and other operations:

from flask import Blueprint, render_template, redirect, url_for, request
from flask_security import login_user, logout_user, current_user, login_required

security_blueprint = Blueprint('security', __name__)


@security_blueprint.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        email = request.form.get('email')
        password = request.form.get('password')
        user = user_datastore.find_user(email=email)
        if user is not None and user.password == password:
            login_user(user)
            return redirect(url_for('index'))
        return redirect(url_for('login'))
    return render_template('login.html')


@security_blueprint.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('index'))


@security_blueprint.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        email = request.form.get('email')
        password = request.form.get('password')
        user = user_datastore.create_user(email=email, password=password)
        user_datastore.add_role_to_user(user, 'user')
        db.session.commit()
        login_user(user)
        return redirect(url_for('index'))
    return render_template('register.html')
Copy after login

Here, we define three view functions: login, logout and register. The login function is used to process user login operations, the register function is used to process user registration operations, and the logout function is used to process user logout operations. Among them, we use the login_user and logout_user functions provided by Flask-Security to implement user login and logout functions. In the register function, we use the user_datastore.create_user and user_datastore.add_role_to_user functions to create a new user and assign it a default user role.

Here, we use Flask's template engine to render HTML pages. For details, please refer to the documentation of Flask template engine.

Finally, we need to register this blueprint in our Flask application:

app.register_blueprint(security_blueprint)
Copy after login

At this point, we have completed using Flask-Security. Now, we can launch our Flask application and access it through the browser.

Summary

In this article, we introduced how to use Flask-Security to add user authentication and password encryption capabilities to Python web applications. By studying this article, we can understand the basic usage of Flask-Security and understand some of its characteristics and precautions. In actual applications, we are free to customize and extend the functionality of Flask-Security to meet our needs.

The above is the detailed content of Flask-Security: Adding user authentication and password encryption to Python web applications. 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
Popular Tutorials
More>
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!