Electron 桌面应用无法验证 Rails CSRF token 如何解决
这个 401 通常跟 Electron 或 TanStack Query 本身无关。生产模式下 win.loadFile('dist/index.html') 会让页面以 file:// 源运行,Rails 的 session cookie 和 CSRF token 就没法像开发模式 http://localhost:3000 那样按同源方式工作。写操作要经过 Rails 的 CSRF 校验;请求没有有效的 X-CSRF-Token,或者没有 session cookie,就会被 Can't verify CSRF token authenticity 拦截。
为什么开发模式正常、Electron 生产模式失败
- 开发模式加载
http://localhost:3000,页面和 Rails 同源,layout 里的csrf_meta_tags能注入 token,session cookie 也会按同源规则发送。 - 生产模式加载
file://.../dist/index.html后,页面 origin 是file://。React 里用 Axios 请求http://localhost:3000或线上 Rails API 时,这就成了跨源请求。Axios 默认不会发送跨源 cookie,得显式设置withCredentials: true。 - 就算请求带上了 cookie,
file://页面也读不到 Rails 注入的meta[name=csrf-token],除非另外通过接口取 token。Rails 默认的 CSRF 校验并不只看 cookie,还需要请求头或参数里的 authenticity token。 - 登录能成功、更新房间却失败,可能是因为登录接口或页面加载路径没有触发同样的写操作 CSRF 校验;更新房间通常是 PATCH/PUT/POST,会触发校验。不要因此就认定 session 没问题。
推荐处理方式
方案一:生产环境也由 Rails 提供页面,保持同源
如果 Electron 只是个壳,生产环境最好别用 loadFile 加载需要访问 Rails session 的页面。让 Rails 提供生产前端页面,Electron 用 loadURL 打开同一个域名,CSRF token、cookie 和 SameSite 都会按同源处理。
const createWindow = () => {
const win = new BrowserWindow({ width: 800, height: 600 });
if (process.env.NODE_ENV === 'development') {
win.loadURL('http://localhost:3000');
} else {
// 生产也让 Rails 提供页面,保持同源
win.loadURL('https://your-app.example.com');
}
};
Rails layout 保留:
<%= csrf_meta_tags %>
Axios 实例设置:
import axios from 'axios';
const api = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL,
withCredentials: true,
});
const meta = document.querySelector<HTMLMetaElement>('meta[name=csrf-token]');
if (meta) {
api.defaults.headers.common['X-CSRF-Token'] = meta.content;
}
export default api;
TanStack Query 的 mutation 继续用这个实例就行:
useMutation({
mutationFn: (room: Room) =>
api.patch(`/rooms/${room.id}`, { status: room.status }),
});
方案二:必须用本地文件时,补上 CORS、cookie 和 token 获取
如果确实要用 file:// 加载页面,就得同时处理跨源请求带凭据、Rails 允许带凭据的 CORS,以及前端主动获取 CSRF token。
Axios 要设置 withCredentials: true。Rails 配置 CORS 时,origin 不能写成 *,还要允许 X-CSRF-Token 请求头:
# Gemfile
gem 'rack-cors'
# config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins 'http://localhost:3000', 'https://your-app.example.com'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head],
credentials: true
end
end
file:// 请求的 Origin 可能是 null。把 null 放进 CORS 白名单有安全风险,不适合作为长期的生产方案。更稳妥的做法是用同源加载、本地 HTTP 服务或自定义协议,并让 Rails 明确允许对应的 origin。
如果页面里拿不到 Rails 的 meta token,可以加一个取 token 的接口:
# config/routes.rb
get '/csrf', to: 'csrf#show'
# app/controllers/csrf_controller.rb
class CsrfController < ApplicationController
def show
render json: { csrfToken: form_authenticity_token }
end
end
前端先带上凭据请求这个接口,再设置请求头:
const { data } = await api.get('/csrf');
api.defaults.headers.common['X-CSRF-Token'] = data.csrfToken;
注意这个 GET 请求也要能带上 session cookie。如果 Set-Cookie 是 SameSite=Lax 或 SameSite=Strict,从 file:// 或跨站页面发起的请求可能带不上 cookie。生产环境通常需要 HTTPS,还要按实际域名检查 SameSite=None; Secure、Domain、Path 等属性。不要为了省事全局 skip_forgery_protection,那等于把 CSRF 防护关掉。
排查顺序
- 先确认失败请求发生在开发模式还是生产模式。开发模式正常、生产模式失败时,重点查
file://和同源环境之间的差异。 - 在 Electron DevTools 的 Network 面板里看更新请求有没有带
Cookie和X-CSRF-Token。 - 确认 Axios 实例有没有设置
withCredentials: true,TanStack Query 的 mutation 是不是真的用了这个实例。 - 查看 Rails 响应和日志里的
Origin、session cookie 以及 CSRF token 校验结果。 - 检查 CORS 的
credentials是否为true,origin 是否不是*,允许的方法和请求头是否覆盖 PATCH/PUT/POST。 - 如果继续用
file://,就得接受它的 origin 限制,并补上 token 获取接口和 cookie 策略。长期方案优先考虑同源加载。
备注:内容仅供参考。
