Electron-vue SessionId 获取

问题描述

使用electron 编写的客户端,一直都是使用 jwt 作为授权凭据,

在网页版一直没有问题。但是集成到Electron 后,注册用户是需要发送验证码,发送验证码和验证验证码的两个接口出现了SessionID不一致的情况。

原因是因为发送验证码时,服务器返回的SessionID 的cookie 没有被保存上,所以,客户端在注册验证时,又出现了新的SessionID。

思路

方法一:前端解决

axios 响应拦截器里获取返回的Set-Cookie,客户端存储,

asxios 请求拦截器里重新设置Cookie

遇到的问题 Set-Cookie 是HttpOnly 无法通过javascript 读取到。不知道还有没有别的办法获取到

方法二:

既然全站都是jwt 通过 header的x-token 来回传递的,那sessionid能否也模拟这个过程呢, 返回的时候通过header 返回,返回服务器的时候也同样携带。

1.后端返回

 /**
 * 发送验证码
 */
    public function  sendCode(){
        $phone = Request::param('phone');
        $vcode = rand(1000,9999);
        // 发送验证码
        Session::set('vcode',$vcode);
        header('session_id:'.session_id());// 后端通过header 返回
        return json(['code' => 20000, 'message' => '已发送'.$vcode]);
    }

2.前端存储

// respone拦截器
axios.interceptors.response.use(
  response => {
    // 获取sessionid
    if (response.headers['session_id']) {
      store.commit('auth/SET_SESSION_ID', response.headers['session_id'])
    }
)

3.前端发送

// request拦截器
axios.interceptors.request.use(config => {
  if (store.state.auth.session_id) {
    // 使用header 传递sessionid
    config.headers['session_id'] = store.state.auth.session_id 
  }
  return config
}

4. 后端获取

public function  Register(){
        $session_id = $this->request->header('session-id');
        session_id($session_id);
        $vcode = Session::get('vcode');
}
上一篇
下一篇