You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Yew中使用Cookie:客户端Rust+Yew应用Cookie处理方法咨询

在Yew客户端应用中设置Cookie存储Auth Token

直接使用web_sys操作原生Cookie API

Yew基于web_sys,可直接调用浏览器原生的document.cookie来操作Cookie,无需额外依赖(Yew项目默认已引入web_sys)。

设置Auth Token到Cookie

use web_sys::{window, Document};

fn set_auth_cookie(token: &str) {
    // 获取浏览器document对象
    let document: Document = window()
        .expect("浏览器环境不存在")
        .document()
        .expect("无法获取document");
    
    // 构建Cookie字符串,按需配置属性
    let cookie = format!(
        "auth_token={}; Path=/; SameSite=Strict; Secure",
        token
    );
    
    // 写入Cookie
    document.set_cookie(&cookie).expect("设置Cookie失败");
}

从Cookie读取Auth Token

use web_sys::{window, Document};

fn get_auth_cookie() -> Option<String> {
    let document = window()?.document()?;
    let cookies = document.cookie().unwrap_or_default();
    
    // 解析Cookie字符串,提取auth_token
    cookies.split(';')
        .map(|s| s.trim())
        .find(|s| s.starts_with("auth_token="))
        .map(|s| s["auth_token=".len()..].to_string())
}

使用cookie crate简化操作

如果需要更规范的Cookie解析和构建,可以用cookie crate封装逻辑:

添加依赖到Cargo.toml

[dependencies]
yew = "0.20"
web-sys = { version = "0.3", features = ["Document", "Window"] }
cookie = "0.17"

封装Cookie操作

use cookie::{Cookie, SameSite};
use web_sys::{window, Document};

fn set_auth_cookie(token: &str) {
    let mut cookie = Cookie::new("auth_token", token);
    cookie.set_path("/");
    cookie.set_same_site(SameSite::Strict);
    cookie.set_secure(true); // HTTPS环境下启用,开发环境可临时注释
    
    let document = window()
        .expect("浏览器环境不存在")
        .document()
        .expect("无法获取document");
    
    document.set_cookie(&cookie.to_string()).expect("设置Cookie失败");
}

fn get_auth_cookie() -> Option<String> {
    let document = window()?.document()?;
    let cookies_str = document.cookie().unwrap_or_default();
    
    // 用cookie crate解析所有Cookie
    Cookie::parse(cookies_str)
        .ok()
        .and_then(|cookie_jar| cookie_jar.get("auth_token").cloned())
}

关键注意事项

  • Secure属性:仅在HTTPS环境生效,生产环境必须启用,避免Cookie明文传输;开发环境用HTTP时可暂时移除。
  • SameSite属性:设为Strict或Lax可防范CSRF攻击,推荐用Strict。
  • 持久化配置:若需要Cookie长期有效,添加Max-Age或Expires属性,比如Max-Age=86400表示1天后过期。
  • HttpOnly属性:客户端脚本无法访问标记为HttpOnly的Cookie,因此如果是客户端设置Auth Token,不要添加该属性;若由后端设置,后端可启用HttpOnly来降低XSS风险。

内容的提问来源于stack exchange,提问作者Mathias Hemmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 22:20:35