You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何借助许可证密钥与验证API实现Flask应用身份认证?

认证方式名称

这种认证方式属于API密钥认证(API Key Authentication)的特定变体,通常称为许可证密钥认证(License Key Authentication)——它以预生成的唯一许可证密钥作为用户的唯一身份凭证,通过第三方服务验证密钥的有效性来授予访问权限。

Flask 实现示例

无需依赖Flask-Security-Too或Flask-Login,通过原生Flask功能即可快速实现:

1. 基础配置与依赖

先安装必要包:

pip install flask requests

2. 核心代码实现

from flask import Flask, render_template_string, request, session, redirect, url_for, abort
import requests

app = Flask(__name__)
app.secret_key = "your-secure-random-key"  # 替换为安全的随机密钥
LICENSE_VALIDATION_API = "https://your-license-api-domain/validate"  # 替换为你的验证API地址

# 简易登录页面模板
LOGIN_TEMPLATE = """
<form method="POST">
    <label>许可证密钥:</label>
    <input type="text" name="license_key" required>
    <button type="submit">登录</button>
</form>
{% if error %}<p style="color:red">{{ error }}</p>{% endif %}
"""

def validate_license(license_key):
    """调用外部API验证许可证有效性"""
    try:
        response = requests.post(LICENSE_VALIDATION_API, data={"license_key": license_key})
        response.raise_for_status()
        result = response.json()
        return result.get("valid", False)  # 假设API返回{"valid": True/False}
    except requests.exceptions.RequestException:
        return False

def requires_valid_license(func):
    """路由装饰器:保护需要授权的页面"""
    def wrapper(*args, **kwargs):
        license_key = session.get("license_key")
        if not license_key or not validate_license(license_key):
            return redirect(url_for("login"))
        return func(*args, **kwargs)
    wrapper.__name__ = func.__name__
    return wrapper

@app.route("/login", methods=["GET", "POST"])
def login():
    error = None
    if request.method == "POST":
        license_key = request.form.get("license_key")
        if validate_license(license_key):
            session["license_key"] = license_key
            return redirect(url_for("protected_page"))
        error = "无效的许可证密钥"
    return render_template_string(LOGIN_TEMPLATE, error=error)

@app.route("/protected")
@requires_valid_license
def protected_page():
    return "这是仅授权用户可访问的页面"

@app.route("/logout")
def logout():
    session.pop("license_key", None)
    return redirect(url_for("login"))

if __name__ == "__main__":
    app.run(ssl_context="adhoc")  # 生产环境请使用正式SSL证书

3. 优化建议

  • 缓存验证结果:使用Redis或本地缓存存储密钥的验证状态,设置过期时间,避免每次请求都调用外部API,减少延迟。
  • 安全传输:强制使用HTTPS,防止密钥在传输过程中被窃取。
  • Session安全:生产环境配置专业的Session存储(如Redis),并开启SESSION_COOKIE_SECURE=True、SESSION_COOKIE_HTTPONLY=True等安全参数。

内容的提问来源于stack exchange,提问作者John Kitchin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 05:45:12