SAP UI5 应用读取 CSRF token 的 HTTP head 请求逻辑解析

JerryWang_汪子熙 -
SAP UI5 应用读取 CSRF token 的 HTTP head 请求逻辑解析

SAP UI5 应用在发送 OData batch 请求之前,会通过下列的_createBatchRequest方法构造 batch 请求对象:

var oBatchRequest = that._createBatchRequest(aReadRequests);

该请求对象的 data 字段里,包含 batch 具体的 payload:

Invoices?$skip=0&$top=100&$orderby=ShipperName%20ascInvoices/$count

该请求头部字段 Accept 为 multipart/mixed:

然后通过 oWrappedBatchRequestHandle.oRequestHandle = that._submitBatchRequest(oBatchRequest, aBatchGroup, fnSuccess, fnError) 方法进行提交。

token handling 标志位为 true,且方法不为 POST,因此在执行 batch 操作之前,先要获取 CSRF token:

进入函数refreshSecurityToken.

构造发起 token 请求的 request 对象:

url 为:https://services.odata.org/V2...

首先尝试 head 请求,如果报错,再切换成 get 请求:

// Initially try method "HEAD", error handler falls back to "GET" unless the flag forbids HEAD request
        if (this.bDisableHeadRequestForToken) {
            mTokenRequest.request = requestToken("GET", handleGetError);
        } else {
            mTokenRequest.request = requestToken("HEAD", handleHeadError);
        }

请求 token 的 HTTP 请求的 Content-type 设置逻辑,和标志位 bJson 有关:

request 对象:

最重要的头部字段 x-csrf-token, 值被填充成 fetch:

function requestToken(sRequestType, fnError) {
            // trigger a read to the service url to fetch the token
            oRequest = that._createRequest(sUrl, "", sRequestType,
                that._getHeaders(undefined, true), null, null, !!bAsync);
            oRequest.headers["x-csrf-token"] = "Fetch";
            return that._request(oRequest, handleSuccess, fnError, undefined, undefined, that.getServiceMetadata());
        }

执行了 head 请求后,响应的状态码是 200,但是 responseText 字段值是空的。

还是进入 success callback:

使用 handler 读取 token 请求的 response,这个 handler 支持的 content-type 类型:application/atomsvc+xml;q=0.8, application/json;odata=fullmetadata;q=0.7, application/json;q=0.5, /;q=0.1

这里因为 response.body 是空的,因此进入不了 dispatchHandler的处理逻辑:

然后进入 refreshToken 的 callback:

当然是拿不到 token 的:

进入 else 分支:

清除所有相关的 token 标志位:

ODataModel.prototype.resetSecurityToken = function() {
        delete this.oSharedServiceData.securityToken;
        delete this.oHeaders["x-csrf-token"];
        delete this.pSecurityToken;
    };

resolve 一个空的 token 给 callback:

这个 head 请求的响应码为 200,但是响应头部没有附带 csrf token:

更多Jerry的原创文章,尽在:"汪子熙":

特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

Tags 标签

javascript前端htmlhtml5sap

扩展阅读

加个好友,技术交流

1628738909466805.jpg