<?xml version="1.0"?>
<policies>
    <inbound>
        <base />
        <send-request ignore-error="false" timeout="20" response-variable-name="response" mode="new">
            <set-url>https://login.microsoftonline.com/{{tenant-id}}/oauth2/v2.0/token</set-url>
            <set-method>POST</set-method>
            <set-header name="Content-Type" exists-action="override">
                <value>application/x-www-form-urlencoded</value>
            </set-header>
            <set-body>@($"grant_type=authorization_code&amp;code={context.Request.OriginalUrl.Query.GetValueOrDefault("code")}&amp;client_id={{client-id}}&amp;client_secret={{client-secret}}&amp;redirect_uri=https://{context.Request.OriginalUrl.Host}/auth/callback";)</set-body>
        </send-request>
        <set-variable name="token" value="@(context.Variables.GetValueOrDefault<IResponse>("response").Body.As<JObject>();)" />
    </inbound>
    <backend />
    <outbound>
        <set-variable name="cookie" value="@{
            var rng = new RNGCryptoServiceProvider();
            var iv = new byte[16];
            rng.GetBytes(iv);
            byte[] tokenBytes = Encoding.UTF8.GetBytes((string)(context.Variables.GetValueOrDefault<JObject>("token"))["access_token"]);
            byte[] encryptedToken = tokenBytes.Encrypt("Aes", Convert.FromBase64String($"{{enc-key}}"), iv);
            byte[] combinedContent = new byte[iv.Length + encryptedToken.Length];
            Array.Copy(iv, 0, combinedContent, 0, iv.Length);
            Array.Copy(encryptedToken, 0, combinedContent, iv.Length, encryptedToken.Length);
            return System.Net.WebUtility.UrlEncode(Convert.ToBase64String(combinedContent));
        }" />
        <return-response>
            <set-status code="302" reason="Temporary Redirect" />
            <set-header name="Set-Cookie" exists-action="override">
                <value>@($"{{cookie-name}}={context.Variables.GetValueOrDefault<string>("cookie")}; Secure; SameSite=Strict; Path=/; Domain={{cookie-domain}}; HttpOnly";)</value>
            </set-header>
            <set-header name="Location" exists-action="override">
                <value>{{return-uri}}</value>
            </set-header>
        </return-response>
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>