新手开发者登录Keystone查看MongoDB时遭遇Invalid CSRF错误求助
Fixing "invalid csrf" Error in Keystone When Accessing MongoDB
Hey there, let's work through this invalid CSRF error you're hitting in Keystone. Since you're new to development, I'll break this down into actionable steps—starting with simple configuration tweaks before diving into the source code bits.
1. Check Keystone's CSRF Origin Configuration
The most common cause of this error is a mismatch between the URL you're accessing Keystone from and the allowed origins in its config. Here's how to fix it:
- Locate your Keystone config file (usually named
keystone.tsorkeystone.config.jsin your project root). - Look for the
serversection, then thecsrfsetting. By default, Keystone restricts CSRF to trusted origins. If you're running locally, explicitly allow your local URL:export default config({ server: { csrf: { // Allow your local development URL and production domain (if applicable) origin: ["http://localhost:3000", "https://your-production-site.com"], }, }, // ... other Keystone configs }); - Note: Only set
csrf: falsetemporarily for local testing (never in production)—this disables CSRF protection entirely and is a security risk.
2. Verify Session Cookie Settings
CSRF validation relies on session cookies, so misconfigured session settings can also trigger this error:
- In your Keystone config, find the
sessionsection. - Ensure the
secureflag is only enabled in production. If you're running locally over HTTP (not HTTPS), settingsecure: truewill prevent the session cookie from being saved:session: { secure: process.env.NODE_ENV === "production", // Only enforce secure cookies in production // ... other session configs (secret, maxAge, etc.) },
3. Dive Into Keystone's CSRF Source Code (If Needed)
If the above fixes don't work, let's look at how Keystone handles CSRF under the hood:
- Navigate to your project's
node_modules/@keystone-6/core/dist/serverfolder (for JavaScript builds) or the source files if you have TypeScript source installed. - Open the
csrf.js(orcsrf.ts) file. Here you'll see the core validation logic:- Keystone checks for the CSRF token in the request header (
X-CSRF-Token) or request body. - It compares this token against the one stored in the user's session cookie.
- Keystone checks for the CSRF token in the request header (
- If you're using a custom frontend (not Keystone's default Admin UI), make sure you fetch the CSRF token from the
/api/csrfendpoint and include it in your request headers—this is handled automatically in the default Admin UI.
4. Quick Local Development Checks
- Stick to one local address: Switching between
localhostand127.0.0.1can cause origin mismatches. Pick one and use it consistently to access Keystone. - Enable browser cookies: Keystone needs session cookies to track the CSRF token. Double-check that your browser isn't blocking cookies from your local development server.
内容的提问来源于stack exchange,提问作者aschmach
相关产品推荐
相关产品推荐

