apifrom.security.csrf

CSRF protection middleware for APIFromAnything.

This module provides middleware for protecting against Cross-Site Request Forgery (CSRF) attacks.

Overview

Classes

Functions

Classes

BaseMiddleware(**options):bases: abc.ABC

Base middleware class for APIFromAnything.

This abstract class defines the interface for middleware components. Middleware components can process requests and responses.

apifrom.security.csrf.options

Options for the middleware.

Type:

dict

Initialize a new BaseMiddleware instance.

param **options:

Options for the middleware.

CSRFMiddleware(secret = None, token_name = 'csrf_token', header_name = 'X-CSRF-Token', cookie_name = 'csrf_token', cookie_path = '/', cookie_secure = True, cookie_http_only = True, cookie_same_site = 'Lax', exempt_methods = None, exempt_routes = None, error_message = 'CSRF token validation failed'):bases: apifrom.middleware.base.BaseMiddleware

Middleware for CSRF protection.

Initialize the CSRF middleware.

param secret:

Secret key for token generation (defaults to a random key)

param token_name:

Name of the token in forms and query parameters

param header_name:

Name of the token header

param cookie_name:

Name of the token cookie

param cookie_path:

Path for the token cookie

param cookie_secure:

Whether the cookie should be secure (HTTPS only)

param cookie_http_only:

Whether the cookie should be HTTP only

param cookie_same_site:

SameSite attribute for the cookie

param exempt_methods:

HTTP methods exempt from CSRF protection

param exempt_routes:

Routes exempt from CSRF protection

param error_message:

Error message for CSRF validation failures

apifrom.security.csrf._generate_token(session_id=None)

Generate a new CSRF token.

param session_id:

The session ID to use for token generation

returns:

The generated token

apifrom.security.csrf._get_session_id(request)

Get the session ID from a request.

param request:

The request to get the session ID from

returns:

The session ID, or None if not found

apifrom.security.csrf._get_token_from_request(request)

Get the CSRF token from a request.

param request:

The request to get the token from

returns:

The CSRF token, or None if not found

apifrom.security.csrf._is_exempt(request)

Check if a request is exempt from CSRF protection.

param request:

The request to check

returns:

True if the request is exempt, False otherwise

Set the CSRF token cookie on a response.

param response:

The response to set the cookie on

param token:

The CSRF token

apifrom.security.csrf._validate_token(token, session_id=None)

Validate a CSRF token.

param token:

The token to validate

param session_id:

The session ID to validate against

returns:

True if the token is valid, False otherwise

apifrom.security.csrf.process_request(request)
:async:

Process a request through the CSRF middleware.

param request:

The request to process

returns:

The processed request

apifrom.security.csrf.process_response(response)
:async:

Process a response through the CSRF middleware.

param response:

The response to process

returns:

The processed response

class apifrom.security.csrf.CSRFToken(secret=None, token_length=32, max_age=3600)[source]
Parameters:
  • secret (Optional[str])

  • token_length (int)

  • max_age (int)

CSRF token generator and validator.

Initialize the CSRF token generator.

param secret:

Secret key for token generation (defaults to a random key)

param token_length:

Length of the token in bytes

param max_age:

Maximum age of tokens in seconds

apifrom.security.csrf._create_signature(data)

Create a signature for the given data.

param data:

The data to sign

returns:

The signature

apifrom.security.csrf.generate_token(session_id=None)

Generate a new CSRF token.

param session_id:

Session ID to bind the token to (optional)

returns:

A new CSRF token

apifrom.security.csrf.validate_token(token, session_id=None)

Validate a CSRF token.

param token:

The token to validate

param session_id:

Session ID to validate against (optional)

returns:

True if the token is valid, False otherwise

JSONResponse(content = None, status_code = 200, headers = None):bases: Response

JSON response for APIFromAnything.

This class represents an HTTP response with JSON content.

Initialize a new JSONResponse instance.

param content:

The response content.

param status_code:

The HTTP status code.

param headers:

HTTP headers.

class apifrom.security.csrf.Request(request=None, path_params=None, method=None, path=None, query_params=None, headers=None, body=None, client_ip=None)[source]
Parameters:
  • request (Optional[starlette.requests.Request])

  • path_params (Optional[dict[Any, Any]])

  • method (Optional[str])

  • path (Optional[str])

  • query_params (Optional[dict[Any, Any]])

  • headers (Optional[dict[Any, Any]])

  • body (Optional[Union[str, bytes]])

  • client_ip (Optional[str])

Request class for APIFromAnything.

This class wraps a Starlette request and provides methods for accessing request data in a convenient way.

apifrom.security.csrf._request

The underlying Starlette request.

apifrom.security.csrf.path_params

Path parameters extracted from the URL.

apifrom.security.csrf.query_params

Query parameters extracted from the URL.

apifrom.security.csrf.headers

HTTP headers.

apifrom.security.csrf.method

HTTP method.

apifrom.security.csrf.path

Request path.

apifrom.security.csrf._body

Cached request body.

Initialize a new Request instance.

param request:

The underlying Starlette request.

param path_params:

Path parameters extracted from the URL.

param method:

The HTTP method.

param path:

The request path.

param query_params:

Query parameters.

param headers:

HTTP headers.

param body:

Request body.

param client_ip:

Client IP address.

class apifrom.security.csrf.Response(content=None, status_code=200, headers=None, content_type='application/json')[source]
Parameters:
  • content (Any)

  • status_code (int)

  • headers (Optional[Dict[str, str]])

  • content_type (str)

Response class for APIFromAnything.

This class represents an HTTP response and provides methods for setting response data, status code, and headers.

apifrom.security.csrf.content

The response content.

apifrom.security.csrf.status_code

The HTTP status code.

apifrom.security.csrf.headers

HTTP headers.

apifrom.security.csrf.content_type

The content type of the response.

Initialize a new Response instance.

param content:

The response content.

param status_code:

The HTTP status code.

param headers:

HTTP headers.

param content_type:

The content type of the response.

Functions

apifrom.security.csrf.csrf_exempt(func)[source]

Decorator to exempt a function from CSRF protection.

param func:

The function to exempt

returns:

The decorated function