Quantcast
Channel: Platform – C# City
Viewing all articles
Browse latest Browse all 16

Authenticating Against Web API from ASP.NET MVC

$
0
0

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);
request.AddObjec(loginViewModel);

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("~/");
}
else
{
    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.


Viewing all articles
Browse latest Browse all 16

Trending Articles