LiveGBS 实现了 GB28181 协议,可以接入各个厂家的监控设备和监控平台,实现统一管理,和 web 端无插件播放,同时支持手机、微信播放。git
LiveGBS 提供简单的登陆鉴权,客户端经过用户名密码登陆成功后,服务端返回认证token的cookie, 后续的接口访问, 服务端从cookie读取token进行校验. 可是, 在与客户系统集成时, 每每须要在客户系统完成鉴权过程. 这时就涉及到跨域的问题. 那么,这一套鉴权过程如何应用到跨域场景中呢?web
服务端处理
服务端须要作如下处理:ajax
-
登陆成功, 服务端主动写 token 到 cookieapi
按照以前的接口设计, 登陆成功, 服务端在 HTTP Response Body 中返回 token,由客户端本身负责将 token 写入 cookie. 在跨域场景中, 这样就行不通了,因为浏览器的限制, 客户端没法将 token 写到非子域名 cookie. 改成服务端主动写 token 到 cookie 就没有这个问题了. 服务端在 HTTP Response Header 中添加
Set-Cookie
字段, 写入token=xxx
跨域 -
服务端统一作充许跨域访问设置浏览器
服务端配置充许跨域而且携带cookie, 须要在 HTTP Response Header 中添加如下两项:微信
Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: $http_origin
Access-Control-Allow-Origin 不能够配置成
*
, 而是当前HTTT前求客户端的 Origincookie -
注销登陆时, 服务端主动将 token 从 cookie 清理dom
Set-Cookie: token=; expires=Thu, 01 Jan 1970 00:00:00 GMT;
客户端处理
客户端没必要显示保存 token 到 cookie. 全部和 LiveGBS 的交互接口须要添加跨域配置, xhrFields: { withCredentials: true }
和 crossDomain: true
url
例如跨域登陆接口调用示例以下:
$.ajax({ type: "GET", url: "http://other-domain/api/v1/login", xhrFields: { withCredentials: true }, crossDomain: true, data: { username: 'admin', password: '21232f297a57a5a743894a0e4a801fc3'//admin }, success: function(data) { console.log(data); } });