Skip to content

[Feature] Option to delete cookie on invalid cookie received #21

Description

@merlinz01

When a user's csrf cookie is invalid for any number of reasons (csrf secret being changed for example), one must go in to the browser dev tools and manually delete the invalid cookie. I'm not a browser security expert so I don't know for sure if there are security implications to doing this, but I find it useful to delete the cookie in the response so that the user can simply refresh the page and try again. Could we have a configuration option to delete invalid csrf cookies?

I am currently doing this:

class CustomCSRFMiddleware(CSRFMiddleware):
    def _get_error_response(self, request: Request) -> Response:
        cookie: http.cookies.BaseCookie = http.cookies.SimpleCookie()
        cookie_name = self.cookie_name
        cookie[cookie_name] = ""
        cookie[cookie_name]["max-age"] = 0
        cookie[cookie_name]["path"] = self.cookie_path
        cookie[cookie_name]["secure"] = self.cookie_secure
        cookie[cookie_name]["httponly"] = self.cookie_httponly
        cookie[cookie_name]["samesite"] = self.cookie_samesite
        if self.cookie_domain is not None:
            cookie[cookie_name]["domain"] = self.cookie_domain
        return JSONResponse(
            {"detail": "CSRF token is missing or invalid."},
            status_code=403,
            headers={"Set-Cookie": cookie.output(header="").strip()},
        )

It would be nice if I could just set a config option:

app.add_middleware(
    CSRFMiddleware,
    delete_invalid_cookie=True,
)

I would be willing to attempt a PR.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions