How authentication works#
- class dmr.security.SyncAuth[source]#
Sync auth base class for sync endpoints.
All auth must support initialization without any required parameters. Auth can have non-required parameters with defaults.
- abstractmethod __call__(endpoint: Endpoint, controller: Controller[BaseSerializer]) Self | None[source]#
Put your auth business logic here.
Return
selfif the login attempt was successful. ReturnNoneif login attempt failed and we need to try another authes. Raisedmr.exceptions.NotAuthenticatedErrorto immediately fail the login without trying other authes. Raisedmr.response.APIErrorif you want to change the return code, for example, when some data is missing or has wrong format.
- provide_response_specs(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]], existing_responses: Mapping[HTTPStatus, ResponseSpec]) list[ResponseSpec]#
Provides responses that can happen when user is not authed.
- abstractmethod security_requirements(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]]) list[SecurityRequirement]#
Provides a security schema usage requirement.
- abstractmethod security_schemes(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]]) dict[str, SecurityScheme | Reference]#
Provides a security schema definition.
- validate(controller_cls: type[Controller[BaseSerializer]], metadata: EndpointMetadata) None#
Validate auth configuration at import time.
Added in version 0.16.0.
- abstract property www_authenticate_challenge: str | None#
Challenge to advertise in
WWW-Authenticateon401responses.RFC 9110 Section 15.5.2 requires every
401to carry at least one challenge, but a challenge can only name an HTTP authentication scheme that the client sends in theAuthorizationheader.Return
Nonewhen there is nothing to advertise: auth that reads credentials from a cookie or from a header of its own cannot express itself as a challenge.Added in version 0.15.0.
- class dmr.security.AsyncAuth[source]#
Async auth base class for async endpoints.
All auth must support initialization without any required parameters. Auth can have non-required parameters with defaults.
- abstractmethod async __call__(endpoint: Endpoint, controller: Controller[BaseSerializer]) Self | None[source]#
Put your auth business logic here.
Return
selfif the login attempt was successful. ReturnNoneif login attempt failed and we need to try another authes. Raisedmr.exceptions.NotAuthenticatedErrorto immediately fail the login without trying other authes. Raisedmr.response.APIErrorif you want to change the return code, for example, when some data is missing or has wrong format.
- provide_response_specs(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]], existing_responses: Mapping[HTTPStatus, ResponseSpec]) list[ResponseSpec]#
Provides responses that can happen when user is not authed.
- abstractmethod security_requirements(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]]) list[SecurityRequirement]#
Provides a security schema usage requirement.
- abstractmethod security_schemes(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]]) dict[str, SecurityScheme | Reference]#
Provides a security schema definition.
- validate(controller_cls: type[Controller[BaseSerializer]], metadata: EndpointMetadata) None#
Validate auth configuration at import time.
Added in version 0.16.0.
- abstract property www_authenticate_challenge: str | None#
Challenge to advertise in
WWW-Authenticateon401responses.RFC 9110 Section 15.5.2 requires every
401to carry at least one challenge, but a challenge can only name an HTTP authentication scheme that the client sends in theAuthorizationheader.Return
Nonewhen there is nothing to advertise: auth that reads credentials from a cookie or from a header of its own cannot express itself as a challenge.Added in version 0.15.0.
- final class dmr.security.SyncOrAsyncAuth(_sync_auth: _SyncAuthT, _async_auth: _AsyncAuthT)[source]#
Auth that selects between a sync and async instance.
Use in global settings to apply a single auth rule to both sync and async endpoints. Not allowed on controller or endpoint level.
Added in version 0.11.0.
Changed in version 0.16.0: Now it is generic.
- dmr.security.request_auth(request: HttpRequest, *, strict: Literal[True]) SyncAuth | AsyncAuth[source]#
- dmr.security.request_auth(request: HttpRequest, *, strict: bool = False) SyncAuth | AsyncAuth | None
Return the auth instance that was used to auth this request.
When strict is passed and request has no auth, we raise
AttributeError.
- dmr.security.add_www_authenticate(exc: NotAuthenticatedError, auth: Sequence[SyncAuth | AsyncAuth] | None) None[source]#
Advertise auth in
WWW-Authenticateon the401that exc returns.RFC 9110 Section 15.5.2 requires every
401to carry at least one challenge. Headers that exc already has always win, so an auth class can raise with a challenge of its own.
- dmr.security.NO_STORE_HEADERS = mappingproxy({'Cache-Control': NewHeader(description='Credentials must not be stored in any cache.', deprecated=False, example=None, value='no-store')})#
- class dmr.security.AuthenticatedHttpRequest[source]#
Annotation for requests that used auth.
Use it for trusted controllers only.
Added in version 0.7.0.
Security#
CSRF#
- class dmr.security.csrf.CSRFSemanticSchemaProvider(*, error_model: TypeForm[Any] = <class 'dmr.errors.ErrorModel'>, status_code: HTTPStatus | None = None, description: str | Promise | None = None, security_scheme_name: str = 'csrf', security_header_scheme_name: str = 'csrf_header', safe_http_methods: Set[HTTPMethod] = frozenset({<HTTPMethod.GET>, <HTTPMethod.HEAD>, <HTTPMethod.OPTIONS>, <HTTPMethod.TRACE>}))[source]#
Provide response specs for controllers that have
csrf_exempt = False.Only provides response specs for controllers that set explicit
csrf_exempt = Falsesetting and define non-safe HTTP endpoints, likepostorput.Should be added to
dmr.settings.Settings.semantic_schema_providerssetting.- error_model#
Error model to be returned. Since CSRF is executed in a middleware before any controller, we can’t get the error model from a controller. This is why this has to be configured separately.
- Type:
typing_extensions.TypeForm[Any]
- status_code#
Status code that should be set for failed CSRF responses.
- Type:
http.HTTPStatus | None
- description#
Human readable description, what the response is for.
- Type:
str | django.utils.functional.Promise | None
- csrf_header_scheme_name#
Security scheme name for the CSRF header scheme (cookie mode only, i.e.
CSRF_USE_SESSIONS = False).
- safe_http_methods#
Set of secure HTTP method names.
Warning
We can’t possibly detect if CSRF enabled for any controller or not. There can be custom middleware, decorators like
@csrf_protect, or evenensure_csrf()inline calls.So, if you know that CSRF is disabled and still want to use
csrf_exempt = Falsefor some reason (?), disable this provider from settings.Added in version 0.16.0.
- merge_security_requirements(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]], own_requirements: list[dict[str, list[str]]], auth_requirements: list[dict[str, list[str]]]) list[dict[str, list[str]]][source]#
Joins CSRF requirement with each auth requirement.
- provide_response_specs(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]], existing_responses: Mapping[HTTPStatus, ResponseSpec]) list[ResponseSpec][source]#
Returns response specs for CSRF endpoints.
- security_requirements(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]]) list[dict[str, list[str]]][source]#
Provides a security schema usage requirement.
- security_schemes(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]]) dict[str, SecurityScheme | Reference][source]#
Provides a security schema definition.
- dmr.security.csrf.build_csrf_handler(prefix: str, /, *prefixes: str, serializer: type[BaseSerializer], format_error: ~dmr.internal.types.FormatError = <function format_error>, renderers: ~collections.abc.Sequence[Renderer] | None = None, status_code: ~http.HTTPStatus = HTTPStatus.FORBIDDEN, languages: ~collections.abc.Sequence[str] | None = None) _CSRFViewProtocol[source]#
Create a CSRF error handler that returns a response with negotiation.
Use this function to build
CSRF_FAILURE_VIEWhandler insettings.py.All prefixes are normalized to start with a leading slash. If the request path matches any of them, a REST response is returned using the same serializer and renderers as your API. If the client’s
Acceptdoes not match any renderer, the first configured renderer is used. For non-matching paths, Django’s defaultCSRF_FAILURE_VIEWhandler is used.- Parameters:
prefix – Path prefix (e.g.
'api/') for which to return API responses.*prefixes – Additional path prefixes.
format_error – Callable used to build the error body for the response.
serializer – Serializer class used to serialize the error body.
renderers – Optional sequence of renderers. If omitted, uses
renderersfrom settings.status_code – Status code to be returned. Defaults to
403.languages – Optional languages that can start the path, like
('en', 'ru')fori18n_patterns. Only these languages are allowed and they must match the path exactly, soendoes not match/en-gb/api/. If omitted, all languages of Django are allowed.
Added in version 0.16.0.
Changed in version 0.17.0: Added
languagesargument.
- dmr.security.csrf.csrf_message(reason: str) str[source]#
Return CSRF failure message according the security rules.
Added in version 0.16.0.
- dmr.security.csrf.csrf_response_spec(*, return_type: TypeForm[Any], status_code: HTTPStatus | None = None, description: str | Promise | None = None) ResponseSpec[source]#
Response spec for CSRF error.
Added in version 0.16.0.
- dmr.security.csrf.csrf_security_scheme(scheme_name: str, header_scheme_name: str) dict[str, SecurityScheme | Reference][source]#
Build the security scheme that describes where the CSRF secret is stored.
By default Django keeps the CSRF secret in the
CSRF_COOKIE_NAMEcookie, so the scheme is anapiKeyincookie.With
CSRF_USE_SESSIONS = TrueDjango requires to send CSRF in a header (CSRF_HEADER_NAME). In that mode there is no separate cookie scheme; the header alone is the complete requirement.- Parameters:
scheme_name – Security scheme name that we use for the CSRF token secret.
header_scheme_name – Security scheme name that we use for the CSRF token value.
Added in version 0.16.0.
Changed in version 0.17.0: Now this function returns a
dictobject of schemes. And accepts the names for these schemes. Now whenCSRF_USE_SESSIONSis defined, we return the header security scheme.
- class dmr.security.csrf.CSRFAuthMixin[source]#
Shared parts of auth classes that are protected by CSRF.
This mixin does all of it. Subclasses only have to:
set
security_scheme_name,csrf_scheme_name, andcsrf_header_scheme_nameattributes,implement
auth_security_scheme()with their own scheme,call
_ensure_csrffrom__call__at the right moment.
Must be listed before the concrete auth base in the class bases, so the methods here win over the default ones.
Added in version 0.16.0.
- abstractmethod auth_security_scheme() SecurityScheme[source]#
Provides the security scheme of the auth itself, without CSRF.
- csrf_security_scheme() dict[str, SecurityScheme | Reference][source]#
Provides the security scheme for CSRF cookie/session storage.
Changed in version 0.17.0: Now this method returns a
dictobject of schemes. Now whenCSRF_USE_SESSIONSis defined, we return the header security scheme.
- provide_response_specs(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]], existing_responses: Mapping[HTTPStatus, ResponseSpec]) list[ResponseSpec][source]#
Declares extra responses for failed auth and failed CSRF checks.
- security_requirements(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]]) list[dict[str, list[str]]][source]#
Requires the auth scheme and CSRF for unsafe HTTP methods.
- security_schemes(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]]) dict[str, SecurityScheme | Reference][source]#
Provides the auth security scheme together with the CSRF one(s).
Semantic schema#
- class dmr.semantic_schema.SecurityProvider[source]#
Provides security schemes and security requirements.
Added in version 0.16.0.
- abstractmethod security_requirements(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]]) list[SecurityRequirement][source]#
Provides a security schema usage requirement.
- abstractmethod security_schemes(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]]) dict[str, SecurityScheme | Reference][source]#
Provides a security schema definition.
- class dmr.semantic_schema.ResponseValidationSpecProvider(*, status_code: HTTPStatus = HTTPStatus.UNPROCESSABLE_ENTITY, description: str | Promise | None = 'Raised when returned response does not match the response schema')[source]#
Provide response specs for response schema validation.
Does not add itself for endpoints that have
validate_responsesturned off.Should be added to
dmr.settings.Settings.semantic_schema_providerssetting.- status_code#
Status code to be returned when validation error happens.
- Type:
- description#
Response spec description for humans.
- Type:
str | django.utils.functional.Promise | None
Added in version 0.16.0.
- provide_response_specs(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]], existing_responses: Mapping[HTTPStatus, ResponseSpec]) list[ResponseSpec][source]#
Provides responses that can happen when returning invalid data.
- class dmr.semantic_schema.SecurityRequirementMerger[source]#
Interface for things that can merge security requirements.
What can do that?
security_mergermerges user providedsecurityrequirements with the ones generated fromauthSemantic schema providers merge their own requirements with the ones generated from
auth, likeCSRFSemanticSchemaProviderdoes
Added in version 0.16.0.
- abstractmethod merge_security_requirements(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]], own_requirements: list[SecurityRequirement], auth_requirements: list[SecurityRequirement]) list[SecurityRequirement][source]#
Merge own security requirements into the auth requirements.
This can implement both
ORandANDlogic depending on the security logic: several alternative requirements meanOR, several schemes in a single requirement meanAND.- Parameters:
metadata – Metadata of the endpoint that is being generated.
controller_cls – Controller class of this endpoint.
own_requirements – Requirements of the thing that merges, for example, user provided
security.auth_requirements – Requirements generated from
auth, already processed by semantic schema providers.
- Returns:
The final list of security requirements for the operation.
- class dmr.semantic_schema.OrSecurityRequirementMerger[source]#
Merge security requirements as alternatives.
All requirements are used as-is, own requirements are added after the auth ones. A client can satisfy any of them, this is what
ORmeans in OpenAPI.This is the default value of
security_merger.- Raises:
EndpointMetadataError – When the same requirement is present more than once in the result. It usually means that
securityrepeats whatauthalready documents.
Added in version 0.16.0.
- merge_security_requirements(metadata: EndpointMetadata, controller_cls: type[Controller[BaseSerializer]], own_requirements: list[SecurityRequirement], auth_requirements: list[SecurityRequirement]) list[SecurityRequirement][source]#
Add own requirements as alternatives to the auth ones.