Implement CSRF protection middleware for API routes#380
Conversation
This middleware checks for CSRF tokens on state-mutating requests and blocks requests if validation fails.
|
Hi @Aditya948351, I have successfully integrated a global CSRF mitigation wrapper inside the src/middleware.ts file to intercept unverified state-mutating request vectors. My Pull Request has been opened! Please review and merge it. Thank you! |
There was a problem hiding this comment.
Some changes needed @nancy-verma780 , while this correctly implements the backend checking mechanism for CSRF, it currently lacks the frontend implementation.
If this PR is merged as-is, it will immediately break all forms, authentications, and state-mutating API requests across the entire application because the frontend does not currently generate, store, or send the x-csrf-token header or csrfToken cookie. All mutating requests will fail with a 403 Forbidden error.
To get this merged, please update the PR to include:
- A mechanism to securely generate and set the csrfToken cookie.
- Updates to our frontend API utilities or fetch wrappers to ensure they read this token and attach the x-csrf-token header to all outgoing POST, PUT, DELETE, and PATCH requests.
This file provides utility functions for handling CSRF tokens and a custom fetch wrapper to include CSRF headers in mutating requests.
|
Hi @Aditya948351, thank you for the feedback! I completely agree that blocking mutating requests without frontend support would halt form submissions.I have updated the PR by implementing a custom frontend helper client inside src/lib/apiClient.ts. It securely structures a client-side csrfToken cookie context configuration layer and builds a custom secureFetch wrapper that reads this cookie token and automatically appends the matching x-csrf-token header to all outgoing POST, PUT, DELETE, and PATCH methods.The code changes are committed directly to this branch. Could you please check out the update? Thank you! |
|
Hi @Aditya948351, thanks for assigning me! I have already implemented the frontend Are there any specific frontend forms or components you want me to explicitly update with this new wrapper before you approve, or should we verify the current setup? Let me know! |
Description
Implemented a centralized request-intercepting middleware inside the
src/directory to block unauthorized state-mutating API calls missing valid CSRF tokens.Closes #359