-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSAPXCSRFTokenPolicy.cshtml
37 lines (36 loc) · 2.45 KB
/
SAPXCSRFTokenPolicy.cshtml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!-- inject in API inbound section to request CSRF -->
<choose>
<!-- CSRF-token only required for every operation other than GET or HEAD -->
<when condition="@(context.Request.Method != "GET" && context.Request.Method != "HEAD")">
<!-- Creating a HEAD subrequest to save request overhead and get the SAP CSRF token and cookie.-->
<send-request mode="new" response-variable-name="SAPCSRFToken" timeout="10" ignore-error="false">
<set-url>@(context.Request.Url.ToString())</set-url>
<set-method>HEAD</set-method>
<set-header name="X-CSRF-Token" exists-action="override">
<value>Fetch</value>
</set-header>
<set-header name="Authorization" exists-action="override">
<!-- forward authorization for csrf token fetch -->
<value>@(context.Request.Headers.GetValueOrDefault("Authorization"))</value>
</set-header>
<!-- Don't expose APIM subscription key to the backend. -->
<set-header name="Ocp-Apim-Subscription-Key" exists-action="delete" />
</send-request>
<!-- Extract the token and cookie from the "SAPCSRFToken" and set as header in the POST request. -->
<set-header name="X-CSRF-Token" exists-action="override">
<value>@(((IResponse)context.Variables["SAPCSRFToken"]).Headers.GetValueOrDefault("x-csrf-token"))</value>
</set-header>
<set-header name="Cookie" exists-action="override">
<value>@{
string rawcookie = ((IResponse)context.Variables["SAPCSRFToken"]).Headers.GetValueOrDefault("Set-Cookie");
string[] cookies = rawcookie.Split(';');
/* new session sends a XSRF cookie */
string xsrftoken = cookies.FirstOrDefault( ss => ss.Contains("sap-XSRF"));
/* existing sessions sends a SessionID. No other cases anticipated at this point. Please create a GitHub Pull-Request if you encounter uncovered settings. */
if(xsrftoken == null){
xsrftoken = cookies.FirstOrDefault( ss => ss.Contains("SAP_SESSIONID"));
}
return xsrftoken.Split(',')[1];}</value>
</set-header>
</when>
</choose>