一个用于 Sanic 框架的异步安全库。
Sanic Security
An async security library for the Sanic framework.Provides authentication, authorization, and verification features including:
Visit security.na-stewart.com for documentation.
In order to get started, please install PyPI (likely included with your Python build).
pip3 install sanic-securityIf 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.
pip3 install sanic-security[crypto]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.
pip3 install sanic-security[oauth]pip3 install sanic-security --upgradeSanic Security configuration is merely a SimpleNamespace that can be modified using dot-notation.
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.
| 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. |
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_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.
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.
You can utilize various OAuth clients based on your needs or customize one. ID and secret should be stored and referenced via configuration.
discord_oauth = DiscordOAuth2(
"1325594509043830895",
"WNMYbkDJjGlC0ej60qM-50tC9mMy0EXa",
)
google_oauth = GoogleOAuth2(
"480512993828-e2e9tqtl2b8or62hc4l7hpoh478s3ni1.apps.googleusercontent.com",
"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",
)@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,
)
)@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@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,
)@app.get("api/security/oauth/token")
@requires_oauth(google_oauth)
async def on_oauth_token(request):
return json(
"Access token retrieved.",
request.ctx.oauth,
)Phone can be null or empty.
| Key | Value |
|---|---|
| username | example |
暂无开放 Issues,或尚未同步最近议题。