Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

sanic-security

> 安全
Open source

An async security library for the Sanic framework.

99 stars0 likes0 views
WebsiteGitHub

About

An async security library for the Sanic framework.

Sanic Security

An async security library for the Sanic framework.

Table of Contents

  • About the Project
  • Getting Started
    • Installation
    • Configuration
  • Usage
    • OAuth
    • Authentication
    • CAPTCHA
    • Two-step Verification
    • Authorization
    • Testing
    • Tortoise
  • Contributing
  • License
  • Versioning

About The Project

Provides authentication, authorization, and verification features including:

  • OAuth2 integration
  • Login, registration, and authentication with refresh mechanisms
  • Image & audio CAPTCHA
  • Two-step verification
  • Role based authorization with wildcard permissions
  • Logging & auditing

Visit security.na-stewart.com for documentation.

Getting Started

In order to get started, please install PyPI (likely included with your Python build).

Installation

  • Install the Sanic Security package.
bash
pip3 install sanic-security
  • Install the Sanic Security package with the cryptography dependency included.

If you're planning on encoding or decoding JWTs using certain digital signature algorithms (like RSA or ECDSA which use the public secret and private secret), you will need to install the cryptography library. This can be installed explicitly, or as an extra requirement.

bash
pip3 install sanic-security[crypto]
  • Install the Sanic Security package with the httpx-oauth dependency included.

If you're planning on utilizing OAuth, you will need to install the httpx-oauth library. This can be installed explicitly, or as an extra requirement.

bash
pip3 install sanic-security[oauth]
  • Update Sanic Security if already installed.
bash
pip3 install sanic-security --upgrade

Configuration

Sanic Security configuration is merely a SimpleNamespace that can be modified using dot-notation.

python
from sanic_security.configuration import config as security_config

security_config.SECRET = "This is a big secret. Shhhhh"
security_config.CAPTCHA_FONT = "resources/captcha-font.ttf"

Environment variables defined with the SANIC_SECURITY_ prefix will be applied to the config. For example, setting SANIC_SECURITY_SECRET will be loaded by the application automatically and fed into the SECRET config variable.

You can load environment variables with a different prefix via security_config.load_environment_variables("NEW_PREFIX_") method.

  • Default configuration values:
Key Value Description
SECRET This is a big secret. Shhhhh The secret used for generating and signing JWTs. This should be a string unique to your application. Keep it safe.
PUBLIC_SECRET None The secret used for verifying and decoding JWTs and can be publicly shared. This should be a string unique to your application.
OAUTH_CLIENT None The client ID provided by the OAuth provider, this is used to identify the application making the OAuth request.
OAUTH_SECRET None The client secret provided by the OAuth provider, this is used in conjunction with the client ID to authenticate the application.
SESSION_SAMESITE Strict The SameSite attribute of session cookies.
SESSION_SECURE True The Secure attribute of session cookies.
SESSION_HTTPONLY True The HttpOnly attribute of session cookies. HIGHLY recommended that you do not turn this off, unless you know what you are doing.
SESSION_DOMAIN None The Domain attribute of session cookies.
SESSION_ENCODING_ALGORITHM HS256 The algorithm used to encode and decode session JWT's.
SESSION_PREFIX tkn Prefix attached to the beginning of session cookies.
MAX_CHALLENGE_ATTEMPTS 3 The maximum amount of session challenge attempts allowed.
CAPTCHA_SESSION_EXPIRATION 180 The amount of seconds till captcha session expiration on creation. Setting to 0 will disable expiration.
CAPTCHA_FONT captcha-font.ttf The file path to the font being used for captcha generation. Several fonts can be used by separating them via comma.
CAPTCHA_VOICE captcha-voice/ The directory of the voice library being used for audio captcha generation.
TWO_STEP_SESSION_EXPIRATION 300 The amount of seconds till two-step session expiration on creation. Setting to 0 will disable expiration.
AUTHENTICATION_SESSION_EXPIRATION 86400 The amount of seconds till authentication session expiration on creation. Setting to 0 will disable expiration.
AUTHENTICATION_REFRESH_EXPIRATION 604800 The amount of seconds till authentication refresh expiration. Setting to 0 will disable refresh mechanism.
ALLOW_LOGIN_WITH_USERNAME False Allows login via username; unique constraint is disabled when set to false.
IP_RECOGNITION True Client will be logged out if ip address is unrecognized.
INITIAL_ADMIN_EMAIL [email protected] Email used when creating the initial admin account.
INITIAL_ADMIN_PASSWORD admin123 Password used when creating the initial admin account.
SMTP_HOSTNAME smtp.example.com The hostname of the SMTP server used for sending emails.
SMTP_USERNAME None The username used to authenticate with the SMTP server.
SMTP_PASSWORD None The password used to authenticate with the SMTP server. Keep it safe.
SMTP_FROM [email protected] The address emails are sent from, and that recipients will see as the sender.
TEMPLATE_PATH email-template.html The file path to the HTML template used when rendering emails. Raw text is sent if the file does not exist.

Usage

Sanic Security's authentication and verification sessions are created for the user after the user logs in or requests some form of verification (two-step, captcha). The session data is then encoded into a JWT and stored on a cookie on the user’s browser. The session cookie is then sent along with every subsequent request. The server can then compare the session stored on the cookie against the session information stored in the database to verify user’s identity and send a response with the corresponding state.

  • Initialize Sanic Security as follows:
python
initialize_security(app)
initialize_oauth(app)  # Remove if not utilizing OAuth
if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8000, workers=1, debug=True)

The tables in the below examples represent example request form-data.

OAuth

Provides users with a familiar experience by having them register/login using their existing credentials from other trusted services (such as Google, Discord, etc.).

This feature is designed to complement existing protocols by linking Sanic Security with the user's OAuth credentials. As a result, developers can leverage robust session handling and account management.

  • Define OAuth clients

You can utilize various OAuth clients based on your needs or customize one. ID and secret should be stored and referenced via configuration.

python
discord_oauth = DiscordOAuth2(
    "1325594509043830895",
    "WNMYbkDJjGlC0ej60qM-50tC9mMy0EXa",
)
google_oauth = GoogleOAuth2(
    "480512993828-e2e9tqtl2b8or62hc4l7hpoh478s3ni1.apps.googleusercontent.com",
    "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",
)
  • Redirect to authorization URL
python
@app.route("api/security/oauth", methods=["GET", "POST"])
async def on_oauth_request(request):
    return redirect(
        await google_oauth.get_authorization_url(
            "http://localhost:8000/api/security/oauth/callback",
            scope=google_oauth.base_scopes,
        )
    )
  • Handle OAuth callback
python
@app.get("api/security/oauth/callback")
async def on_oauth_callback(request):
    token_info, authentication_session = await oauth_callback(
        request, google_oauth, "http://localhost:8000/api/security/oauth/callback"
    )
    response = json(
        "Authorization successful.",
        {"token_info": token_info, "auth_session": authentication_session.json},
    )
    oauth_encode(response, token_info)
    authentication_session.encode(response)
    return response
  • Get access token
python
@app.get("api/security/oauth/token")
async def on_oauth_token(request):
    token_info = await decode_oauth(request, google_oauth)
    return json(
        "Access token retrieved.",
        token_info,
    )
  • Requires access token (This method is not called directly and instead used as a decorator)
python
@app.get("api/security/oauth/token")
@requires_oauth(google_oauth)
async def on_oauth_token(request):
    return json(
        "Access token retrieved.",
        request.ctx.oauth,
    )

Authentication

  • Registration (with two-step email verification)

Phone can be null or empty.

Key Value
username example
email

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Pythonaiohttpasyncauthauthentication

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category安全
PricingOpen source

> Related tools

O
OWASP ZAP
开源 Web 应用安全扫描器
O
owasp-wstg-tracker
Simple web app to track OWASP WSTG security testing progress
H
homebridge-mi-gateway-security
XiaoMi Gateway Security plugin for HomeBridge.