Authenticating Against Web API from ASP.NET MVC

In a previous post, we talked about setting up ASP.NET MVC and Web API to accept forms authentication.

With this structure in place, your MVC front-end can make Web API calls. The question is, how do you authenticate? What cookies do you need to pass around?

There are actually two sets of cookies involved:

  • The MVC side has its own authentication cookies (.ASPXAUTH)
  • The Web API returns two cookies: an empty .AspNet.ExternalCookie one, and a .AspNet.ApplicationCookie one.

It’s this latter cookie that you need to pass to your API client to authenticate any subsequent calls. When you receive them, you need to store them somewhere (I used the session).

Here’s the call to log in to the API:

var client = new RestClient("/api");
var request = new RestRequest("Account/LogIn", Method.POST);

var response = client.Execute(request)

if (response.StatusCode == HttpStatusCode.OK)
    Session["AuthCookies"] = response.Cookies;
    FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe);
    HttpContext.User = new GenericPrincipal(new GenericIdentity(model.Email), null);
    return Redirect("~/");
    ModelState.AddModelError("", "Invalid login attempt.");
    return View(model);

Notice we’re saving the response’s cookies in Session["AuthCookies"].

Once we have those, we pass them to any subsequent API calls:

var client = new RestClient("/api");

var cookies = Session["AuthCookies"] as IList<RestResponseCookie>;
if (cookies != null)
    client.CookieContainer = new System.Net.CookieContainer();

    foreach (var cookie in cookies)
        client.CookieContainer.Add(new System.Net.Cookie(cookie.Name, cookie.Value, cookie.Path, cookie.Domain));

// build a request object
var response = client.Execute(request);

I don’t think storing Web API authentication cookies in the session is a good idea (it opens you up to session hijacking). If you know a more secure way to manage the authentication cookies, please share it in a comment.

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Libraries, Web and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *