Try our conversational search powered by Generative AI!

Rejaie
Dec 18, 2017
  4310
(2 votes)

Web API + Service API + Cookie Auth Gotcha

I ran into an interesting problem while on a past project this year - when we turned on Service API via OWIN, my authorized Web API endpoints were returning a 401. We were using cookie authentication for the Web API endpoints. This baffled me a bit until I peeled back the code for Service API.

When one of the Service API's initialization modules executes, it bypasses the default host authentication by calling SupportDefaultHostAuthentication on the Global HTTP Configuration. This explains why my API endpoints weren't recognizing the logged in user's cookie. I came up with a workaround that ignored this call and used cookie authentication instead. See below - during this project, we were using Episerver 10.9.1, and Service API 3.0.1:

  • Add the following code to your OWIN startup. This code ultimately re-adds cookie auth to the Web API filter pipeline

    GlobalConfiguration.Configuration.Filters.Add(new HostAuthenticationFilter(DefaultAuthenticationTypes.ApplicationCookie));
  • In your API controller, decorate your controller or action with the System.Web.Http's Authorize Attribute

After I made these changes, I was able to access my authorized Web API endpoints. As a quick note, if you do use cookie authentication for your Web API endpoints, you may want to send an antiforgery token to protect against XSRF attacks. In this project, I sent the antiforgery token as a header and created a filter attribute that validated the token against the logged in user's cookie. In case anyone is interested, here was my setup:

  • In my master layout, I included a global antiforgery token. I placed this right after the <body> tag, but you can place this anywhere.

  • In my client side code, I sent the antiforgery token as a header. I called the __RequestVerificationToken.

  • On the server side, I created an attribute called UserValidateAntiForgeryTokenAttribute that inherited from FilterAttribute and IAuthorizationFilter. In the ExecuteAuthorizationFilterAsync method, I grabbed the cookie and token values and validated them against each other.
    public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext,
                CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
            {
                try
                {
                    // get headers
                    var headers = actionContext.Request.Headers;
    
                    // get cookie value
                    var cookieRvtValue = headers
                        .GetCookies()
                        .Select(c => c[AntiForgeryConfig.CookieName])
                        .FirstOrDefault()
                        ?.Value;
    
                    // get header value
                    var headerRvtValue = headers.GetValues("__RequestVerificationToken").FirstOrDefault();
    
                    // validate
                    AntiForgery.Validate(cookieRvtValue, headerRvtValue);
                }
                catch
                {
                    actionContext.Response = new HttpResponseMessage
                    {
                        StatusCode = HttpStatusCode.Forbidden,
                        RequestMessage = actionContext.ControllerContext.Request
                    };
                    var source = new TaskCompletionSource<HttpResponseMessage>();
                    source.SetResult(result);
                    return source.Task;
                }
                return continuation();
            }
        }
  • Decorate your Web API controller action with the attribute

    [UserValidateAntiForgeryToken]
    [Authorize]
    [HttpGet]
    public string DoGetAction()
    {
         // do something
         return string.empty;
    }
    

Thanks for reading. Hope you find this helpful!

Dec 18, 2017

Comments

Morten Holmgaard
Morten Holmgaard Jan 29, 2018 12:59 PM

It does not work for me - episerver does not have the same logged in context. What else do you have in web.config and in OWIN startup file?

Please login to comment.
Latest blogs
Solving the mystery of high memory usage

Sometimes, my work is easy, the problem could be resolved with one look (when I’m lucky enough to look at where it needs to be looked, just like th...

Quan Mai | Apr 22, 2024 | Syndicated blog

Search & Navigation reporting improvements

From version 16.1.0 there are some updates on the statistics pages: Add pagination to search phrase list Allows choosing a custom date range to get...

Phong | Apr 22, 2024

Optimizely and the never-ending story of the missing globe!

I've worked with Optimizely CMS for 14 years, and there are two things I'm obsessed with: Link validation and the globe that keeps disappearing on...

Tomas Hensrud Gulla | Apr 18, 2024 | Syndicated blog

Visitor Groups Usage Report For Optimizely CMS 12

This add-on offers detailed information on how visitor groups are used and how effective they are within Optimizely CMS. Editors can monitor and...

Adnan Zameer | Apr 18, 2024 | Syndicated blog

Azure AI Language – Abstractive Summarisation in Optimizely CMS

In this article, I show how the abstraction summarisation feature provided by the Azure AI Language platform, can be used within Optimizely CMS to...

Anil Patel | Apr 18, 2024 | Syndicated blog

Fix your Search & Navigation (Find) indexing job, please

Once upon a time, a colleague asked me to look into a customer database with weird spikes in database log usage. (You might start to wonder why I a...

Quan Mai | Apr 17, 2024 | Syndicated blog