CSRFConfig¶
CSRF extends for Cross-Site Request Forgery and it is one of the built-in middlewares of Esmerald.
When a CSRFConfig object is passed to an application instance, it will automatically start the CSRFMiddleware
.
Tip
More information about CSRF here.
CSRFConfig and application¶
To use the CSRFConfig in an application instance.
from esmerald import CSRFConfig, Esmerald, settings
csrf_config = CSRFConfig(
secret=settings.secret_key,
cookie_name="csrftoken",
)
app = Esmerald(csrf_config=csrf_config)
Another example
from esmerald import CSRFConfig, Esmerald, settings
csrf_config = CSRFConfig(
secret_key=settings.secret_key, session_cookie="csrftoken", header_name="x-csrftoken"
)
app = Esmerald(csrf_config=csrf_config)
Parameters¶
All the parameters and defaults are available in the CSRFConfig Reference.
CSRFConfig and application settings¶
The CSRFConfig can be done directly via application instantiation but also via settings.
from esmerald import CSRFConfig, EsmeraldAPISettings, ImproperlyConfigured
class CustomSettings(EsmeraldAPISettings):
@property
def csrf_config(self) -> CSRFConfig:
"""
Initial Default configuration for the CSRF.
This can be overwritten in another setting or simply override `secret`
or then override the `def csrf_config()` property to change the behavior
of the whole csrf_config.
"""
if not self.secret_key:
raise ImproperlyConfigured("`secret` setting not configured.")
return CSRFConfig(secret=self.secret_key)
This will make sure you keep the settings clean, separated and without a bloated Esmerald instance.