const state = Math.random().toString(36).substr(2);逐步解析
Math.random() // 生成 0~1 之间的随机小数,如: 0.7123456789
.toString(36) // 转为 36 进制字符串 (0-9 + a-z),如: "0.p8j2k4m..."
.substr(2) // 从索引 2 开始截取,去掉 "0.",如: "p8j2k4m..."
为什么需要 state 参数?
在 OAuth 授权流程中:
用户发起请求时,生成随机
state并存储(如 sessionStorage)将
state附加到微信授权 URL微信回调时会原样返回这个
state前端验证回调的
state是否与之前存储的一致
作用:确保回调请求确实来自你发起的授权流程,而非恶意第三方伪造的请求。
更现代的写法(可选学习)
substr() 已被废弃,现代 JS 推荐用:
// 方法1:substring
const state = Math.random().toString(36).substring(2);
// 方法2:slice
const state = Math.random().toString(36).slice(2);
// 方法3:crypto.randomUUID()(浏览器支持)
const state = crypto.randomUUID();