百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

增强 FastAPI 安全性:实现安全标头

itomcoil 2024-12-22 18:54 39 浏览

FastAPI 是一个现代 Web 框架,用于基于标准 Python 类型提示使用 Python 3.7+ 构建 API。虽然它提供了许多强大的功能并且设计为安全的,但您可以采取其他措施来进一步增强 FastAPI 应用程序的安全性。其中一项措施是实现安全标头。安全标头可以帮助保护您的应用程序免受各种攻击,例如跨站点脚本 (XSS)、点击劫持和内容嗅探。在本博客中,我们将讨论一些基本的安全标头以及如何在 FastAPI 应用程序中实现它们。

了解安全标头

在深入实现之前,让我们先了解一些关键的安全标头是什么以及它们的作用:

  1. 内容安全策略 (CSP):通过指定允许加载哪些内容源来帮助防止 XSS 攻击。
  2. 严格传输安全 (HSTS):确保浏览器仅通过 HTTPS 与服务器通信。
  3. X-Content-Type-Options:防止浏览器将文件解释为与指定不同的 MIME 类型。
  4. X-Frame-Options:通过控制页面是否可以显示在框架中来防止点击劫持。
  5. Referrer-Policy:控制请求中包含多少引荐来源信息。
  6. X-XSS-Protection:启用大多数现代 Web 浏览器中内置的跨站点脚本 (XSS) 过滤器。

在 FastAPI 中实现安全标头

FastAPI 不提供对设置安全标头的内置支持,但使用中间件添加它们很简单。FastAPI 中的中间件是在每个请求之前或之后运行的函数。以下是创建和添加中间件以设置安全标头的方法。

步骤 1:创建中间件以添加安全标头

创建一个名为 middleware.py 的文件并定义一个中间件函数来添加安全标头。

from starlette.middleware.base import BaseHTTPMiddleware
from starlette.types import ASGIApp, Receive, Scope, Send


class SecurityHeadersMiddleware(BaseHTTPMiddleware):
    def __init__(self, app: ASGIApp):
        super().__init__(app)


    async def dispatch(self, request: Scope, call_next):
        response = await call_next(request)
        
        # Add security headers
        response.headers['Content-Security-Policy'] = "default-src 'self'"
        response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
        response.headers['X-Content-Type-Options'] = 'nosniff'
        response.headers['X-Frame-Options'] = 'DENY'
        response.headers['Referrer-Policy'] = 'no-referrer'
        response.headers['X-XSS-Protection'] = '1; mode=block'
        
        return response

步骤 2:将中间件添加到您的 FastAPI 应用程序

在您的FastAPI 应用程序主文件(例如 main.py)中,导入并添加中间件。

from fastapi import FastAPI
from middleware import SecurityHeadersMiddleware


app = FastAPI()


# Add SecurityHeadersMiddleware to the application
app.add_middleware(SecurityHeadersMiddleware)


@app.get("/")
async def root():
    return {"message": "Hello, World!"}

步骤 3:运行您的应用程序

使用 uvicorn 运行您的 FastAPI 应用程序。

uvicorn main:app --reload

现在,当您访问您的 FastAPI 应用程序时,指定的安全标头将包含在响应中。您可以通过检查浏览器的开发人员工具中的响应标头或使用 curl 等工具来验证这一点。

示例验证

使用 curl 发出请求并查看响应标头。

curl -I http://127.0.0.1:8000/

您应该在响应中看到安全标头:

HTTP/1.1 200 OK
content-security-policy: default-src 'self'
strict-transport-security: max-age=31536000; includeSubDomains
x-content-type-options: nosniff
x-frame-options: DENY
referrer-policy: no-referrer
x-xss-protection: 1; mode=block

除了前面展示的一般实现之外,下面还有一些关于在 FastAPI 中实现各种安全标头的其他演示。这些演示将介绍不同标头的具体用例,以及如何微调它们以满足应用程序的安全需求。

1. 具有多个指令的内容安全策略 (CSP)

内容安全策略 (CSP) 标头通过指定允许哪些内容源来帮助防止 XSS 攻击。在这里,我们演示了如何设置更详细的 CSP 策略。

步骤 1:定义中间件

from starlette.middleware.base import BaseHTTPMiddleware
from starlette.types import ASGIApp, Receive, Scope, Send


class CSPMiddleware(BaseHTTPMiddleware):
    def __init__(self, app: ASGIApp):
        super().__init__(app)


    async def dispatch(self, request: Scope, call_next):
        response = await call_next(request)
        # Detailed CSP policy
        csp_policy = (
            "default-src 'self'; "
            "script-src 'self' https://trustedscripts.example.com; "
            "style-src 'self' https://trustedstyles.example.com; "
            "img-src 'self' data:;"
        )
        response.headers['Content-Security-Policy'] = csp_policy
        return response

步骤2:将中间件添加到 FastAPI 应用程序

from fastapi import FastAPI
from csp_middleware import CSPMiddleware


app = FastAPI()


app.add_middleware(CSPMiddleware)


@app.get("/")
async def root():
    return {"message": "Hello, Secure World!"}

2. Feature-Policy 标头

Feature-Policy 标头允许您控制哪些功能和 API 可在浏览器中使用。

步骤 1:定义中间件

from starlette.middleware.base import BaseHTTPMiddleware
from starlette.types import ASGIApp, Receive, Scope, Send


class FeaturePolicyMiddleware(BaseHTTPMiddleware):
    def __init__(self, app: ASGIApp):
        super().__init__(app)


    async def dispatch(self, request: Scope, call_next):
        response = await call_next(request)
        # Set Feature-Policy header
        feature_policy = (
            "geolocation 'none'; "
            "midi 'none'; "
            "sync-xhr 'self'; "
            "microphone 'none'; "
            "camera 'none'; "
            "magnetometer 'none'; "
            "gyroscope 'none'; "
            "speaker 'self'; "
            "vibrate 'none'; "
            "fullscreen 'self'; "
            "payment 'none';"
        )
        response.headers['Feature-Policy'] = feature_policy
        return response

步骤 2:将中间件添加到 FastAPI 应用程序

from fastapi import FastAPI
from feature_policy_middleware import FeaturePolicyMiddleware


app = FastAPI()


app.add_middleware(FeaturePolicyMiddleware)


@app.get("/")
async def root():
    return {"message": "Hello, Feature-Policy World!"}

3. Referrer-Policy 标头

Referrer-Policy 标头控制请求中包含多少引荐来源信息。

步骤 1:定义中间件

from starlette.middleware.base import BaseHTTPMiddleware
from starlette.types import ASGIApp, Receive, Scope, Send


class ReferrerPolicyMiddleware(BaseHTTPMiddleware):
    def __init__(self, app: ASGIApp):
        super().__init__(app)


    async def dispatch(self, request: Scope, call_next):
        response = await call_next(request)
        # Set Referrer-Policy header
        response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
        return response

步骤 2:将中间件添加到 FastAPI 应用程序

from fastapi import FastAPI
from referrer_policy_middleware import ReferrerPolicyMiddleware


app = FastAPI()


app.add_middleware(ReferrerPolicyMiddleware)


@app.get("/")
async def root():
    return {"message": "Hello, Referrer-Policy World!"}

4. Permissions-Policy 标头(以前称为 Feature-Policy)

Permissions-Policy 标头(以前称为 Feature-Policy)控制哪些浏览器功能可在您的应用程序中使用。

步骤 1:定义中间件

from starlette.middleware.base import BaseHTTPMiddleware
from starlette.types import ASGIApp, Receive, Scope, Send


class PermissionsPolicyMiddleware(BaseHTTPMiddleware):
    def __init__(self, app: ASGIApp):
        super().__init__(app)


    async def dispatch(self, request: Scope, call_next):
        response = await call_next(request)
        # Set Permissions-Policy header
        permissions_policy = (
            "accelerometer=(), "
            "camera=(), "
            "geolocation=(), "
            "gyroscope=(), "
            "magnetometer=(), "
            "microphone=(), "
            "payment=(), "
            "usb=()"
        )
        response.headers['Permissions-Policy'] = permissions_policy
        return response

步骤 2:将中间件添加到 FastAPI 应用程序

from fastapi import FastAPI
from permissions_policy_middleware import PermissionsPolicyMiddleware


app = FastAPI()


app.add_middleware(PermissionsPolicyMiddleware)


@app.get("/")
async def root():
    return {"message": "Hello, Permissions-Policy World!"}

5. 自定义安全标头中间件

您可以创建一个允许您根据需要设置自定义标头的中间件。

步骤 1:定义中间件

from starlette.middleware.base import BaseHTTPMiddleware
from starlette.types import ASGIApp, Receive, Scope, Send


class CustomHeadersMiddleware(BaseHTTPMiddleware):
    def __init__(self, app: ASGIApp, headers: dict):
        super().__init__(app)
        self.headers = headers


    async def dispatch(self, request: Scope, call_next):
        response = await call_next(request)
        for header, value in self.headers.items():
            response.headers[header] = value
        return response

步骤 2:将中间件添加到 FastAPI 应用程序

from fastapi import FastAPI
from custom_headers_middleware import CustomHeadersMiddleware


app = FastAPI()


custom_headers = {
    'X-DNS-Prefetch-Control': 'off',
    'X-Download-Options': 'noopen',
    'X-Permitted-Cross-Domain-Policies': 'none',
}


app.add_middleware(CustomHeadersMiddleware, headers=custom_headers)


@app.get("/")
async def root():
    return {"message": "Hello, Custom Headers World!"}

通过实现这些额外的安全标头,您可以显著增强 FastAPI 应用程序的安全态势。自定义中间件可让您根据安全需求的变化轻松添加、修改和管理这些标头。

实施安全标头是一种简单而有效的增强 FastAPI 应用程序安全性的方法。通过使用中间件添加这些标头,您可以保护您的应用程序免受常见的安全威胁,例如 XSS、点击劫持和 MIME 类型嗅探。

写在最后:

  1. 如上所述,安全标头增强了安全性,改进了对功能的控制等,但是,过度的安全标头也是一种“灾难”,标头本身就增加了每个请求的处理逻辑,可能降低性能;过度的限制对于用户的体验是一种伤害,也可能误伤合法内容或者功能,所以安全是一个道,大家要慎重的去平衡

相关推荐

selenium(WEB自动化工具)

定义解释Selenium是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE(7,8,9,10,11),MozillaF...

开发利器丨如何使用ELK设计微服务中的日志收集方案?

【摘要】微服务各个组件的相关实践会涉及到工具,本文将会介绍微服务日常开发的一些利器,这些工具帮助我们构建更加健壮的微服务系统,并帮助排查解决微服务系统中的问题与性能瓶颈等。我们将重点介绍微服务架构中...

高并发系统设计:应对每秒数万QPS的架构策略

当面试官问及"如何应对每秒几万QPS(QueriesPerSecond)"时,大概率是想知道你对高并发系统设计的理解有多少。本文将深入探讨从基础设施到应用层面的解决方案。01、理解...

2025 年每个 JavaScript 开发者都应该了解的功能

大家好,很高兴又见面了,我是"高级前端进阶",由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发。1.Iteratorhelpers开发者...

JavaScript Array 对象

Array对象Array对象用于在变量中存储多个值:varcars=["Saab","Volvo","BMW"];第一个数组元素的索引值为0,第二个索引值为1,以此类推。更多有...

Gemini 2.5编程全球霸榜,谷歌重回AI王座,神秘模型曝光,奥特曼迎战

刚刚,Gemini2.5Pro编程登顶,6美元性价比碾压Claude3.7Sonnet。不仅如此,谷歌还暗藏着更强的编程模型Dragontail,这次是要彻底翻盘了。谷歌,彻底打了一场漂亮的翻...

动力节点最新JavaScript教程(高级篇),深入学习JavaScript

JavaScript是一种运行在浏览器中的解释型编程语言,它的解释器被称为JavaScript引擎,是浏览器的一部分,JavaScript广泛用于浏览器客户端编程,通常JavaScript脚本是通过嵌...

一文看懂Kiro,其 Spec工作流秒杀Cursor,可移植至Claude Code

当Cursor的“即兴编程”开始拖累项目质量,AWS新晋IDEKiro以Spec工作流打出“先规范后编码”的系统工程思维:需求-设计-任务三件套一次生成,文档与代码同步落地,复杂项目不...

「晚安·好梦」努力只能及格,拼命才能优秀

欢迎光临,浏览之前点击上面的音乐放松一下心情吧!喜欢的话给小编一个关注呀!Effortscanonlypass,anddesperatelycanbeexcellent.努力只能及格...

JavaScript 中 some 与 every 方法的区别是什么?

大家好,很高兴又见面了,我是姜茶的编程笔记,我们一起学习前端相关领域技术,共同进步,也欢迎大家关注、点赞、收藏、转发,您的支持是我不断创作的动力在JavaScript中,Array.protot...

10个高效的Python爬虫框架,你用过几个?

小型爬虫需求,requests库+bs4库就能解决;大型爬虫数据,尤其涉及异步抓取、内容管理及后续扩展等功能时,就需要用到爬虫框架了。下面介绍了10个爬虫框架,大家可以学习使用!1.Scrapysc...

12个高效的Python爬虫框架,你用过几个?

实现爬虫技术的编程环境有很多种,Java、Python、C++等都可以用来爬虫。但很多人选择Python来写爬虫,为什么呢?因为Python确实很适合做爬虫,丰富的第三方库十分强大,简单几行代码便可实...

pip3 install pyspider报错问题解决

运行如下命令报错:>>>pip3installpyspider观察上面的报错问题,需要安装pycurl。是到这个网址:http://www.lfd.uci.edu/~gohlke...

PySpider框架的使用

PysiderPysider是一个国人用Python编写的、带有强大的WebUI的网络爬虫系统,它支持多种数据库、任务监控、项目管理、结果查看、URL去重等强大的功能。安装pip3inst...

「机器学习」神经网络的激活函数、并通过python实现激活函数

神经网络的激活函数、并通过python实现whatis激活函数感知机的网络结构如下:左图中,偏置b没有被画出来,如果要表示出b,可以像右图那样做。用数学式来表示感知机:上面这个数学式子可以被改写:...