编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

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

wxchong 2024-11-10 12:16:22 开源技术 17 ℃ 0 评论

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

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表