generate_challenge

gafaelfawr.auth.generate_challenge(context, auth_type, exc, scopes=None, *, error_in_headers=True)

Convert an exception into an HTTP error with WWW-Authenticate.

Always return a status code of 401 or 403, even if we want to return a different status code to the client, but put the actual status code in X-Error-Status. This works around limitations of the NGINX auth_request module, which can only handle 401 and 403 status codes. The status code will be retrieved from the headers and fixed by custom NGINX configuration in an error_page location.

Similarly, put the actual body of the error in X-Error-Body so that it can be retrieved and sent to the client. Normally, NGINX discards the body returned by an auth_request handler.

Parameters:
  • context (RequestContext) – The context of the incoming request.

  • auth_type (AuthType) – The type of authentication to request.

  • exc (OAuthBearerError) – An exception representing a bearer token error.

  • scopes (set[str] | None, default: None) – Optional scopes to include in the challenge, primarily intended for InsufficientScopeError exceptions.

  • error_in_headers (bool, default: True) – Whether to put the actual error status in X-Error-Status instead of raising it. Disable this for OpenID Connect routes.

Returns:

A prepopulated fastapi.HTTPException object ready for raising. The headers will contain a WWW-Authenticate challenge.

Return type:

fastapi.HTTPException