Add Optimizely CMS user access filtering to the ASP.NET and C# proxy example

To filter predictions by user access rights, you can modify the proxy endpoint that handles the prediction URL.

This example code loads the Rek.ai JSON response and filters it based on the current user's access.

Add the access check

First, add this method to perform the check. Depending on your URL configuration, you might need to validate the format and possibly append a trailing slash to the URL before creating the UrlBuilder.

private static bool HasAccess(string url, IUrlResolver urlResolver)
{
    var content = urlResolver.Route(new UrlBuilder(url));
 
    if (content == null)
    {
        // This will remove predictions that have no matching page
        return false;
    }
 
    if (content is ISecurable securable)
    {
        var securityDescriptor = securable.GetSecurityDescriptor();
        return securityDescriptor.HasAccess(PrincipalInfo.CurrentPrincipal, AccessLevel.Read);
    }
 
    return true;
}

Replace the prediction endpoint

Then replace endpoints.MapGet("/rest-api/rek/{*remainder}") with this version.

This version checks the number of predictions requested in the CMS block, then doubles it to avoid returning too few items after filtering. Evaluate whether this formula works for your application, and adjust it if needed.

endpoints.MapGet("/rest-api/rek/{*remainder}", async (string remainder, IHttpClientFactory httpClientFactory, IUrlResolver urlResolver, HttpContext context) =>
    {
        var queryString = context.Request.QueryString.Value ?? string.Empty;
 
        // Add secret key parameter to back-channel URL
        var queryValues = QueryHelpers.ParseQuery(queryString);
        queryValues["srek"] = siteSettings.RekSecretKey;
 
        // This is just a fallback value; the URL will most likely already contain a value
        var originalNumber = 12;
 
        if (int.TryParse(queryValues["nr"], out var parsedNumber))
        {
            originalNumber = parsedNumber;
 
            // Read nr and increase it
            queryValues["nr"] = (parsedNumber * 2).ToString(CultureInfo.InvariantCulture);
        }
 
        var predictUrl = QueryHelpers.AddQueryString($"https://predict.rekai.se/{remainder?.Replace("proxypredict", "predict").TrimStart('/')}", queryValues);
 
        using var message = new HttpRequestMessage(HttpMethod.Get, predictUrl);
 
        AddRekProxyRequestHeaders(context, message);
 
        var httpClient = httpClientFactory.CreateClient("RekProxyPredict");
        using var response = await httpClient.SendAsync(
            message,
            HttpCompletionOption.ResponseHeadersRead,
            context.RequestAborted).ConfigureAwait(false);
 
        context.Response.StatusCode = (int)response.StatusCode;
        context.Response.ContentType = response.Content.Headers.ContentType?.ToString() ?? "application/json";
 
        // Read into JSON and filter the items
        JsonNode jsonNode;
 
        try
        {
            await using var responseStream = await response.Content.ReadAsStreamAsync(context.RequestAborted).ConfigureAwait(false);
            jsonNode = await JsonNode.ParseAsync(responseStream, cancellationToken: context.RequestAborted).ConfigureAwait(false);
        }
        catch (JsonException)
        {
            return Results.BadRequest("Invalid JSON response.");
        }
 
        if (jsonNode is null)
        {
            return Results.BadRequest("Response body cannot be empty.");
        }
 
        if (jsonNode is JsonObject jsonObject
            && jsonObject["predictions"] is JsonArray predictions)
        {
            var predictionsWithUrls = new List<(JsonNode Prediction, string Url)>();
 
            // Collect all prediction URLs
            foreach (var prediction in predictions)
            {
                if (prediction is JsonObject predictionObject
                    && predictionObject["url"] is JsonValue urlValue
                    && urlValue.TryGetValue<string>(out var url))
                {
                    predictionsWithUrls.Add((prediction, url));
                }
            }
 
            // Check all items and only keep items that user has read-access for
            foreach (var (prediction, url) in predictionsWithUrls)
            {
                if (!HasAccess(url, urlResolver))
                {
                    predictions.Remove(prediction);
                }
            }
 
            // Remove any items above the max number of predictions
            while (predictions.Count > originalNumber)
            {
                predictions.RemoveAt(predictions.Count - 1);
            }
        }
 
        return Results.Json(jsonNode);
    });