简单示例 flask-login 基于 request_loader 方法的 token 登录

Flask Web开发入门(三)之使用 Request Loader 定制登录 在上一章中,我们介绍了使用Flask-Login进行会话管理,实现基本的登入、登出功能,在实际的业务运用中,不仅要求基本的登录登出授权管理,还要求对外暴漏API接口服务,当然暴漏的服务接口不可能随意访问,还需要一定的授权信息,这时,我们需要Request Loader来进行定制登录,简单期间,我们使用HTTP Header中的Authorization作为查询参数的API密钥,只有请求Header 阅读详情

效果图: 



Flask-Login is a Flask extension that provides a framework for handling user authentication.This post will give you a basic tutorial of the Flask-Login mechanism for token based authentication.

The goal of this post is to give a very basic introduction to token based authentication using Flask-Login.Usually the user credentials are stored in a database, with passwords hashed. However the authenticationmechanism can be understood without having to worry about database, and various token generation algorithms.As a first step lets focus on just understanding the authentication mechanism. Then in a subsequent postwe will handle other important parts.

To run this example, you will need flask and flask-login with their dependencies installed.This can be done usingpip as shown below:

>pip install flask
>pip install flask-login

Example Code

Here is the full source code that we are about to discuss:

# Author: Gouthaman Balaraman

# http://gouthamanbalaraman.com/minimal-flask-login-example.html



from flask import Flask, Response

from flask.ext.login import LoginManager, UserMixin, login_required

app = Flask(__name__)

login_manager = LoginManager()

login_manager.init_app(app)

class User(UserMixin):

# proxy for a database of users

     user_database = {"JohnDoe": ("JohnDoe","John"),

                             "JaneDoe": ("JaneDoe","Jane")}

    def __init__(self,username,password):

        self.id = username

        self.password = password



    @classmethod

    def get(cls,id):

        return cls.user_database.get(id)

@login_manager.request_loader

def load_user(request):

    token = request.headers.get('Authorization')

    if token is None:

        token = request.args.get('token')

    if token is not None:

        username,password = token.split(":")# naive token

        user_entry = User.get(username)

        if (user_entry is not None):

             user = User(user_entry[0],user_entry[1])

            if (user.password == password):

            return user

    return None




@app.route("/",methods=["GET"])

def index():

        return Response(response="Hello World!",status=200)


@app.route("/protected/",methods=["GET"])

@login_required

def protected():

    return Response(response="Hello Protected World!",status=200)


if __name__ == '__main__':

    app.config["SECRET_KEY"]="ITSASECRET"

    app.run(port=5000,debug=True)




view raw flask_login_token.py hosted with ❤ by GitHub

Code Explained

Lets delve deeper into this example, and I will explain each part of the code in greater detail here.

from flask import Flask, Response
from flask.ext.login import LoginManager, UserMixin, login_required

app = Flask(__name__)
login_manager = LoginManager()
login_manager.init_app(app)


The first five lines of the code import the required modules, and initializes the Flaskapp. ThentheLoginManager instance is created and then is configure for login. Now lets try to understandtheUser class.

class User(UserMixin):
    # proxy for a database of users
    user_database = {"JohnDoe": ("JohnDoe", "John"),
               "JaneDoe": ("JaneDoe", "Jane")}

    def __init__(self, username, password):
        self.id = username
        self.password = password

    @classmethod
    def get(cls,id):
        return cls.user_database.get(id)

Here I have created the User class by overloading theUserMixin class. TheUserMixin classimplements some of the default methods, and hence is a convenient starting point. Thedictuser_databaseis a proxy for all the database code one would need. I am abstracting this away as adict for simplicity.Theget class method returns the user data fromuser_database.

For the LoginManager to handle authentication, we have to provide a method for it to load user.Here I use the generic@login_manager.request_loader decorator to decorate theload_user function.The expected behavior of a request_loader is to return aUser instance if the provided credentials arevalid, and returnNone otherwise.

@login_manager.request_loader
def load_user(request):
    token = request.headers.get('Authorization')
    if token is None:
        token = request.args.get('token')

    if token is not None:
        username,password = token.split(":") # naive token
        user_entry = User.get(username)
        if (user_entry is not None):
            user = User(user_entry[0],user_entry[1])
            if (user.password == password):
                return user
    return None

The load_user looks for a token in Authorization header, or the request arguments. If a tokenis provided, then I return an instance ofUser if the token is valid, and returnNone otherwise.Here I assume that a valid token would be of the form<username>:<password>. This is a naive token,and should not be used in practice. Using serializers fromitsdangerous package can come handy. Wewill touch upon these issues in another post.

Once this setup is done, in order to require authentication for a route, use the@login_requireddecorator.

Run the above script, and if you visit the LocalHostUnAuthenticated route withouta token you will get a 401 Unauthorized message. If you pass a token toLocalHostAuthenticated, then you will be allowed access to the protected page.

Conclusion

This article explained how to write token based authentication using Flask-Login extension. The focusof this article was explaining the basic workings offlask-login without having to setup database oreven the token generation. Once the basic plumbing is setup, one can extend this example in two ways:




flask 利用token 进行登录效验 网站、小程序、APP 是否已经登录所代表的状态,代表一个概念是登录态。我们常用的登录态验证方式主要是如下3种 cookie,session,tokencookie和session 采用的是缓存机制,是需要在浏览器端或服务器端,储存用户登录状态。两者的特点,cookie 采用的浏览器缓存 相对于 session 采用的服务器缓存机制安全较差,但后者很怕用户过多给服务器代理过大的压力。token 提供了另外一种不需要缓存账户和密码的登录状态验证方式。 阅读详情

相关推荐

别再瞎调了!手把手教你用Temperature和Top-p让ChatGPT输出更靠谱

本文详细解析了如何通过调整Temperature和Top-p等关键参数优化ChatGPT的输出质量。从技术文档到创意写作,不同场景下的参数设置策略和实战示例,帮助用户精准控制生成内容的严谨性与创造性,避免常见输出问题。

weixin_30596735的博客 456

使用Flask-Login实现token验证和超时失效使用体会

使用Flask-Login实现token验证和超时失效

C~C的小世界 1万+

Flask-Login 实战指南:从会用到精通的登录状态管理

HTTP 协议天然无状态,而 Web 应用必须持续识别用户身份——这正是会话管理(session management)的核心命题。Flask-Login 作为 Flask 生态中轻量、稳定、可调试的认证状态维护方案,其本质是通过 session 或 remember me cookie 实现用户对象的跨请求绑定与惰性加载。它不处理密码哈希或 OAuth 流程,专注解决‘当前是谁’这一基础能力,从而支撑权限校验、登录拦截、多端状态同步等关键场景。本文深入剖析 user_loader 回调机制、remembe

weixin_30315905的博客 385

[python]Flask_Login

flask login的介绍与使用

weixin_67719939的博客 1830

Flask-Login 认证原理与生产级实践指南

Web 应用认证(Authentication)是保障用户身份可信传递的基础机制,其核心在于建立 request-response 循环中稳定、安全的身份上下文。Flask-Login 并非全自动登录插件,而是通过标准化 session 管理、用户对象生命周期控制和权限钩子集成,实现可扩展的身份状态治理。它不处理密码校验或数据库交互,专注解决‘验证后如何持续识别用户’这一关键问题。技术价值体现在解耦认证逻辑与业务代码、支持 remember me、fresh login、2FA 扩展等场景。典型应用包括后台

weixin_30307921的博客 448

Flask-Login实战避坑指南:Vue前后端分离下的登录态管理

Flask-Login是Python Web开发中用于用户会话管理的基础认证扩展,其核心原理是通过session绑定用户ID并配合user_loader回调实现请求级身份识别。它不处理密码校验或Token生成,而是专注‘已验证用户’在多次HTTP请求中的状态延续,技术价值在于轻量、可插拔且深度适配Flask上下文机制。典型应用场景包括图书管理系统、内部后台、教育平台等需角色隔离的B端应用;尤其在Flask与Vue前后端分离架构中,必须协同配置SameSite=None、Secure Cookie、withC

weixin_34133829的博客 362

Flask-Login用户认证系统实现与安全实践

用户认证是Web开发的基础安全机制,通过会话管理实现身份验证与授权控制。Flask-Login作为Python生态的轻量级解决方案,采用装饰器模式简化了登录状态管理流程,其核心原理包括用户加载器机制、会话保护中间件和Remember Me功能实现。在工程实践中,该扩展能有效防御CSRF攻击和会话劫持,同时支持与SQLAlchemy等ORM无缝集成。典型的应用场景包括电商平台会员系统、SaaS应用多租户隔离以及API服务的JWT签发。本文以Flask-Login为例,详解如何通过login_required装

weixin_34332905的博客 470

Flask认证体系从零构建:Session、JWT与Flask-Login深度实践

Web认证是保障应用安全的基石,其核心在于身份识别(Authentication)与会话管理(session)的可靠协同。原理上,服务端需通过加密签名、状态校验与生命周期控制,确保用户身份不可伪造、登录态不可劫持。技术价值体现在可审计性、抗攻击性(如防XSS、CSRF、时序攻击)及跨架构适配能力。典型应用场景包括内部管理系统、前后端分离图书平台、政务内网系统等,尤其在Flask-Vue架构中需权衡session与JWT的使用边界。本文聚焦Flask生态下真实落地的认证方案,深入解析Flask-Login契约

weixin_33728708的博客 419

Flask-Login用户认证机制详解与实践指南

用户认证是Web开发中的基础安全机制,通过会话管理实现身份验证与授权控制。Flask-Login作为Flask生态的核心扩展,采用客户端会话cookie存储用户标识,配合装饰器实现路由保护,其user_loader机制完成会话到用户对象的转换。在工程实践中,该技术方案既保证了开发效率,又通过current_user代理统一处理认证状态。典型应用场景包括后台管理系统、API服务认证等,特别适合需要快速实现安全认证的中小型项目。通过合理配置remember me功能和会话保护策略,可以平衡安全性与用户体验。本文

weixin_33851604的博客 352

Flask-Login用户认证实战:从配置到生产部署

用户认证是Web开发的核心模块,Flask-Login作为Flask生态的标准认证解决方案,通过简洁的API实现了会话管理、访问控制等基础功能。其底层原理基于Werkzeug的安全Cookie和Flask的请求上下文,支持包括密码认证、API密钥等多种验证方式。在工程实践中,该扩展特别适合需要快速实现RBAC权限系统的场景,配合SQLAlchemy等ORM工具可以轻松构建企业级用户体系。本文以Flask-Login为核心,详解如何实现多因素认证、会话保护等生产级功能,并分享登录流程优化、安全配置等实战经验。

weixin_30847865的博客 448

Flask-Login实战指南:轻量级Web身份认证核心原理与安全落地

Web身份认证是Python后端开发的基础能力,其本质是解决用户会话状态的持久化、安全性与跨请求一致性问题。核心原理在于服务端通过Session或Token标识用户身份,并结合Cookie实现浏览器端状态绑定,技术价值体现在降低安全风险(如CSRF、会话劫持)、提升开发效率及保障多端体验一致性。典型应用场景包括后台管理系统登录保护、用户个性化内容展示、权限分级访问控制等。Flask-Login作为Flask生态事实标准,以极简接口封装session生命周期管理、remember me自动续期、匿名用户统一处

weixin_33911824的博客 367

Flask新手注册系统实战:从零搭建安全可用的用户注册流程

用户注册是Web应用最基础的身份入口,其本质是HTTP表单提交、服务端验证、密码安全存储与数据库持久化的完整闭环。理解这一流程需掌握请求响应机制、CSRF防护原理、密码哈希必要性及SQLite轻量事务特性。技术价值在于以最小依赖(Flask+Werkzeug+WTForms+SQLite)实现防重复、防明文、防伪造的核心安全能力,适用于内部工具登录、MVP产品验证、教学实验等低并发但高可靠需求场景。本文聚焦真实新手视角,详解如何绕过Django/FastAPI等重型框架,用原生Flask构建可运行、可调试、

weixin_34082854的博客 440

Flask-Login实战:从零构建安全可扩展的用户会话体系

用户身份认证是Web应用的基础能力,其核心在于理解HTTP会话(session)与浏览器Cookie的协同机制、服务端状态保持原理,以及密码安全哈希等关键技术价值。在Python Web开发中,Flask-Login并非黑盒插件,而是聚焦于‘请求间身份延续’这一本质问题的轻量级解决方案,广泛应用于图书管理系统、后台管理平台及前后端分离架构中。它与Flask-SQLAlchemy深度协同,通过user_loader回调解耦数据层与认证逻辑,同时支持JSON API与传统模板渲染双模式。本文围绕真实生产场景,详

weixin_30561425的博客 443

Django、Flask、Tornado框架选型实战指南

Web框架是构建服务端应用的核心基础设施,其本质是HTTP请求处理、路由分发、中间件编排与异步IO调度的技术载体。理解Django的全栈约定、Flask的显式可拆卸设计和Tornado的单线程事件循环原理,有助于规避N+1查询、上下文丢失、连接池耗尽等高频工程陷阱。三者技术价值迥异:Django胜在开箱即用的生产就绪能力,Flask强于轻量嵌入与微服务解耦,Tornado专精高并发长连接场景。典型应用场景包括内部管理系统(Django admin)、边缘设备API(Flask单文件部署)、实时协作服务(To

weixin_33901926的博客 366

Flask-Login认证原理与工程实践:从会话管理到等保合规

Web身份认证是保障应用安全的基石,其核心在于用户状态的可靠持久化、跨请求的身份一致性以及会话生命周期的可控管理。Flask-Login并非简单封装登录逻辑,而是基于Werkzeug上下文机制,提供符合RFC6265 Cookie规范和OWASP ASVS标准的标准化认证骨架。它通过login_required装饰器统一访问控制策略,利用current_user实现线程安全的身份透传,并内置session_protection机制防御会话劫持。在图书管理系统、医疗预约平台等真实场景中,它显著降低因手写ses

diankui6178的博客 324

Flask-Login核心机制与实战避坑指南

Flask-Login是Python Web开发中实现用户会话管理的关键组件,其本质是一套基于Session的状态协议,而非简单的登录功能封装。它通过`_user_id`会话键、`UserMixin`契约接口和`current_user`动态代理三者协同,在无状态HTTP上构建有状态认证流。技术价值在于解耦认证逻辑与业务代码,支撑从头歌实验到生产级图书管理系统、智能租房平台等多场景落地。典型应用场景包括单体应用登录保护、Vue前后端分离的跨域会话同步、RESTful API的权限分层控制。本文聚焦`is_a

weixin_30600197的博客 370

基于Flask与rkdeveloptool的RK开发板Web OTA升级系统实战

OTA(Over-The-Air)升级技术是嵌入式设备实现远程固件更新的核心机制,它通过网络传输取代了传统的物理连接方式,其原理在于设备端运行一个服务端程序来接收、验证并应用新的固件包。这项技术的核心价值在于极大地提升了设备运维的效率和可管理性,尤其适用于部署在远端或需要批量更新的物联网、工业控制等应用场景。本文将聚焦于**RK系列开发板**,通过集成**rkdeveloptool**命令行工具与Python Flask Web框架,构建一个完整的浏览器端固件烧写解决方案。该系统将复杂的烧写流程封装为简洁的

weixin_34268753的博客 653

Flask用户认证系统实战:从密码哈希到会话管理的完整实现

用户认证是现代Web应用的基础安全机制,其核心原理是通过验证用户身份来建立访问控制。在技术实现上,通常涉及密码学哈希、会话管理和权限验证等关键技术。密码哈希加盐技术能确保用户凭证的安全存储,有效抵御彩虹表攻击;而会话管理则通过Cookie和服务器端状态维护用户的登录状态。这些技术的工程实践价值在于为应用构建了可靠的安全边界,防止未授权访问和数据泄露。在Python Web开发领域,Flask框架因其轻量灵活的特性,常被用于构建此类认证系统。本文以Flask-Login和Flask-WTF等扩展库为例,详细解

wangqiaowqo的专栏 548
上一篇: CentOS7.3安装Python3.6
下一篇: Flask SQLAlchemy 脚本测试方法
SmallTankPy
博客等级 码龄10年 26粉丝 15原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值