DEV Community

Cover image for Introducing Secweb security headers for fastapi and starlette framework
tmotagam
tmotagam

Posted on • Updated on

Introducing Secweb security headers for fastapi and starlette framework

UPDATE

Secweb has been updated it now uses ASGI Middleware implementation which means no more ContextVar problems and also improved performance creating very less overhead in using the library than before.

What is Secweb ?

Secweb is a library of middlewares that helps you in setting security headers in fastapi and starlette framework.

Why to use Secweb ?

Secweb makes it easy to add security headers or to change those headers parameters without you having to get your hands into the intricacies of the starlette framework so you can write your bussines logic without any worries and it also secures all of your apis.

How to use Secweb

First we will install the library using the pip command, You can use any packaging manager system you like eg. poetry, conda, pipenv, etc. to name a few.

pip install Secweb
Enter fullscreen mode Exit fullscreen mode

Now you can import it into any of your existing or new fastapi or starlette projects, I am creating a new dummy fastapi project for this blog.

Example:

from fastapi import FastAPI
from Secweb import SecWeb

app = FastAPI()
SecWeb(app=app)

@app.get("/")
async def root():
    return {"message": 'Hello World'}
Enter fullscreen mode Exit fullscreen mode

Now your api is secured by the secweb it is this easy to add Secweb into your projects all the important headers are activated by the secweb eg. Content Security Policy (CSP), Strict Transport Security (HSTS), etc. to name a few, If you want you can even change all the headers parameters according to your needs don't worry all the other headers are also activated with their default settings so that you don't unnecessarily increase security risk of your apis.

Example:

from fastapi import FastAPI
from Secweb import SecWeb

app = FastAPI()
SecWeb(app=app, Option={'hsts': {'max-age': 432000, 'includeSubDomains': True, 'preload': False}})

@app.get("/")
async def root():
    return {"message": 'Hello World'}
Enter fullscreen mode Exit fullscreen mode

All the headers are also available as standalone in the library for you to use remember using only the standalone headers will only activate those headers others will remain deactivated.

Example:

from fastapi import FastAPI
from ContentSecurityPolicyMiddleware import ContentSecurityPolicy

app = FastAPI()
app.add_middleware(ContentSecurityPolicy, Option={'style-src': 'self'}, style_nonce=style_nonce)

@app.get("/")
async def root():
    return {"message": 'Hello World'}
Enter fullscreen mode Exit fullscreen mode

For more information on all the headers provided by the Secweb library you can go to Github to read the detailed documentation.

Hope this helps you in your projects 👋 Bye.

Top comments (0)