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

ASP.NET非MVC应用存AccessToken到Cookie并调用Graph API获取OneDrive数据咨询

操作实现方案

1. 令牌存储到Cookie的正确操作

你拿到的JWT响应中,需要存储的核心字段为access_token、refresh_token、expires_on,存储时需严格配置Cookie安全属性,避免令牌泄露:

  • 所有存储令牌的Cookie必须开启HttpOnly属性,禁止前端JS读取,防范XSS攻击窃取令牌
  • 生产环境必须开启Secure属性,仅允许Cookie在HTTPS协议下传输
  • 设置SameSite = Strict属性,防范CSRF攻击
  • access_token对应的Cookie有效期设置为expires_in对应的秒数,refresh_token对应的Cookie有效期可设置为30天(匹配常规refresh_token默认有效期规则)
  • 不要存储id_token等非必要字段到Cookie,减少不必要的信息泄露风险

示例配置(Express后端场景):

// 存储访问令牌
res.cookie('graph_access_token', accessToken, {
  httpOnly: true,
  secure: process.env.NODE_ENV === 'production',
  sameSite: 'strict',
  maxAge: Number(expires_in) * 1000
})
// 存储刷新令牌
res.cookie('graph_refresh_token', refreshToken, {
  httpOnly: true,
  secure: process.env.NODE_ENV === 'production',
  sameSite: 'strict',
  maxAge: 30 * 24 * 60 * 60 * 1000 // 30天
})
// 存储过期时间戳
res.cookie('graph_token_expires_on', expires_on, {
  httpOnly: true,
  secure: process.env.NODE_ENV === 'production',
  sameSite: 'strict',
  maxAge: 30 * 24 * 60 * 60 * 1000
})

2. 调用Graph API时读取Cookie内令牌的操作

  • 前端发起资源请求时,浏览器会自动携带HttpOnly Cookie,无需前端手动处理令牌
  • 后端接收请求后,首先从Cookie中读取graph_access_token和graph_token_expires_on
  • 校验令牌有效性:将当前时间戳(秒级)和expires_on对比,若当前时间小于expires_on,直接使用该令牌发起Graph API请求
  • 发起Graph API请求时,在请求头中添加字段:Authorization: Bearer ${access_token}

3. 令牌刷新的正确操作

触发刷新的条件

  • 当前时间戳大于等于expires_on,令牌已过期
  • 调用Graph API时返回401 Unauthorized状态码,说明令牌失效

刷新流程

  • 从Cookie中读取graph_refresh_token
  • 向OAuth2授权服务的令牌端点发起POST请求,携带参数:
    • grant_type = refresh_token
    • client_id = 你的应用注册ID
    • client_secret = 你的应用密钥(机密客户端场景必填,公开客户端无需填写)
    • refresh_token = 读取到的刷新令牌
    • scope = 和首次申请令牌时一致的权限范围
  • 刷新请求成功后,会返回新的access_token、refresh_token、expires_on,按照步骤1的规则更新对应Cookie即可
  • 若刷新请求失败(如refresh_token也已过期、被吊销),直接终止流程,引导用户重新登录授权

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 00:54:02