网站开发制作公司,互联网企业分类,太原网站优化怎么做,企业网络营销信息源类别及传递渠道调查基本认证#xff08;Basic Authentication#xff09;#xff1a;
这是一种简单的鉴权方式#xff0c;需要客户端发送用户名和密码#xff0c;服务器验证后允许或拒绝访问。可以使用 Flask-BasicAuth 扩展来实现。首先#xff0c;安装扩展#xff1a;
pip install Fla…基本认证Basic Authentication
这是一种简单的鉴权方式需要客户端发送用户名和密码服务器验证后允许或拒绝访问。可以使用 Flask-BasicAuth 扩展来实现。首先安装扩展
pip install Flask-BasicAuthfrom flask import Flask
from flask_basicauth import BasicAuthapp Flask(__name__)
app.config[BASIC_AUTH_USERNAME] admin
app.config[BASIC_AUTH_PASSWORD] 123456
app.config[BASIC_AUTH_FORCE] False # 为True 就默认对所有 api 进行认证 如果设置为 False 那么可以通过 basic_auth.required 对指定 api 进行认证。
basic_auth BasicAuth(app)app.route(/)
basic_auth.required
def hello_world():return Hello World!此时访问鉴权的接口地址会要求输入用户名密码 使用代码请求样例
import requestsurl http://192.168.3.199:7130payload{}
headers {User-Agent: Apifox/1.0.0 (https://apifox.com),Authorization: Basic YWRtaW46MTIzNDU2
}response requests.request(GET, url, headersheaders, datapayload)print(response.text)
密文处实际为base64加密
auth str(base64.b64encode(f{self.username}:{self.password}.encode(utf-8)), utf-8)
headers {
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0, Content-Type: application/json, Authorization: fBasic {auth}
}Token 鉴权(todo)
客户端在请求中携带一个令牌token服务器验证该令牌是否有效。这种方式通常用于API鉴权。可以使用 Flask-JWT-Extended 或 Flask-RESTful 等扩展来实现。 通过 Token 鉴权是一种常见的方式用于保护 Web 应用或 API 的安全性。在 Flask 中你可以使用第三方扩展如 Flask-JWT-Extended 来实现 Token 鉴权。以下是一个基本的示例
首先安装 Flask-JWT-Extended 扩展
pip install Flask-JWT-Extendedfrom flask import Flask, request
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identityapp Flask(__name__)# 设置密钥用于加密 Token
app.config[JWT_SECRET_KEY] your_secret_key# 初始化 JWTManager
jwt JWTManager(app)# 路由用于用户登录并生成 Token
app.route(/login, methods[POST])
def login():username request.json.get(username)password request.json.get(password)# 这里应该根据用户名和密码验证用户# 如果验证成功创建并返回一个 Tokenif username user and password password:access_token create_access_token(identityusername)return {access_token: access_token}else:return {message: Invalid credentials}, 401# 受保护的路由需要 Token 鉴权
app.route(/protected, methods[GET])
jwt_required()
def protected_route():current_user get_jwt_identity()return fHello, {current_user}! This route is protected by JWT.if __name__ __main__:app.run()
我们使用 Flask-JWT-Extended 来处理 Token 鉴权。 在 /login 路由中用户提供用户名和密码进行验证。如果验证成功将创建并返回一个包含用户身份信息的 Token。 在 /protected 路由中我们使用了 jwt_required() 装饰器它要求请求中必须包含有效的 Token 才能访问。 你需要将上述示例中的用户名和密码验证部分替换为你实际的用户验证逻辑。请确保在生产环境中使用 HTTPS 来保护通信安全并考虑其他安全性措施如 Token 过期时间、刷新 Token 等。
自定义装饰器(todo)
你可以编写自己的装饰器函数来实现鉴权逻辑。例如下面是一个简单的自定义装饰器示例
from flask import Flask, request, jsonify
from functools import wrapsapp Flask(__name__)# 用户认证函数根据用户名和密码验证用户
def authenticate(username, password):# 实际应用中这里应该根据用户名和密码进行验证if username user and password password:return Truereturn False# 自定义装饰器函数用于鉴权
def auth_required(f):wraps(f)def decorated_function(*args, **kwargs):auth request.authorizationif not auth or not authenticate(auth.username, auth.password):return jsonify({message: Authentication required}), 401return f(*args, **kwargs)return decorated_functionapp.route(/)
auth_required
def protected_route():return This route is protected by custom authentication.if __name__ __main__:app.run()