Tauri+Better Auth的跨域问题
编辑问题说明
如果是普通网页中的Better Auth
那只需要前后端部署在同一域名下即可, 例如使用nginx
部署前端+反向代理后端; 如果是SSR
那本身就是全栈不存在跨域问题, 如果是原生应用则没有CORS
跨域问题, 只需要考虑cookie兼容即可。 只有Tauri
这种环境下会比较麻烦, 它无法像Electron
一样轻易的关闭跨域校验, 所以一般从服务端下手。
允许跨域
如果后端直接暴露端点, 那么应该在应用层解决跨域问题, 手动添加Access-Control-Allow-*
一系列响应头。例如搜索Express允许跨域
、Fastify允许跨域
关键字, 当然还一些一点需要注意, 建议看完全文。
或者在一般情况下为了复用443
端口会在套一层Nginx
, 在这种情况下就应该在Nginx
中配置跨域, 由于我使用的是OpenResty
直接支持Lua
, 因此我的解决跨域配置如下:
access_by_lua_block {
local allowed_origins = {
["http://tauri.localhost"] = true,
["http://localhost:14200"] = true
}
local origin = ngx.var.http_origin
if origin and allowed_origins[origin] then
ngx.header["Access-Control-Allow-Origin"] = origin
ngx.header["Access-Control-Allow-Credentials"] = "true"
ngx.header["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS, PUT, DELETE"
ngx.header["Access-Control-Allow-Headers"] = "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization"
ngx.header["Access-Control-Max-Age"] = 1728000
end
if ngx.req.get_method() == "OPTIONS" and origin and allowed_origins[origin] then
ngx.exit(ngx.HTTP_NO_CONTENT)
end
}
如果你使用的是Nginx
可以把上述配置发送给AI,让它改写成Nginx
的配置。
跨域配置注意事项
上述Access-Control-Allow-Origin
不能直接设置为*
, 因为在Access-Control-Allow-Credentials
为true
的情况下浏览器为了安全要求(防止CSRF
攻击)Access-Control-Allow-Origin
必须设置为具体值。
这里设置的http://tauri.localhost
和http://localhost:14200
是Tauri
在生产和开发环境下的Origin
跨域配置总结
Access-Control-Allow-Origin
是允许浏览器发起跨域请求
Access-Control-Allow-Credentials
是允许浏览器发起跨域请求时携带cookie
allowed_origins
保证了只有tauri
环境下才允许跨域
Better Auth配置
trustedorigins配置
在Better Auth
中还有一个 trustedorigins配置, 该配置也是为了防止CSRF
攻击。
上面的OpenResty
配置作用在浏览器层面, 下述Better Auth
配置作用在应用层层面, 因此这里也要进行配置, 否则调用Better Auth
接口时会报403
:
{
trustedOrigins: [
'http://localhost:14200',
'http://tauri.localhost',
],
}
samesite配置
Better Auth
默认情况下cookie设置的 samesite 为Lax
, 在该配置也是在防止CSRF
攻击, 该配置下Tauri
中发起的请求不会携带Cookie
, 所以还需要配置:
{
advanced: {
defaultCookieAttributes: {
sameSite: 'none',
secure: true,
partitioned: true,
},
},
}
合并后配置如下:
export const auth = betterAuth({
trustedOrigins: [
'http://localhost:14200',
'http://tauri.localhost',
],
advanced: {
defaultCookieAttributes: {
sameSite: 'none',
secure: true,
partitioned: true,
},
},
})
总结
首先在OpenResty
中配置服务器在Tauri
环境下允许跨域请求, 请求时允许发送Cookie, 但是是否真的能够自动携带Cookie
发起请求还受制于samesite
配置, 最后应用层也会校验Origin
, 因此还需要配置trustedorigins
。
- 0
- 0
-
分享