Asp.net-mvc – MVC .NET cookie authenticated system acessing a Web Api with token authentication

asp.net-mvcasp.net-web-apibearer-tokenowin

I have a Mvc 5 client that have a Ownin cookie authentication.
I also have a Web Api that is protected with Owin Bearer token (I used the VS2013 Web Api template, that create the Token endpoint)

Ok, now my Mvc 5 client need to use my WebApi.
I created a method to get the bearer token:

internal async Task<string> GetBearerToken(string siteUrl, string Username, string Password)
{
     HttpClient client = new HttpClient();

     client.BaseAddress = new Uri(siteUrl);
     client.DefaultRequestHeaders.Accept.Clear();

     HttpContent requestContent = new StringContent("grant_type=password&username=" + Username + "&password=" + Password, Encoding.UTF8, "application/x-www-form-urlencoded");

     HttpResponseMessage responseMessage = await client.PostAsync("Token", requestContent);

     if (responseMessage.IsSuccessStatusCode)
     {
         TokenResponseModel response = await responseMessage.Content.ReadAsAsync<TokenResponseModel>();
         return response.AccessToken;
     }

     return "";
}

And in my Mvc action I called that:

public async Task<ActionResult> Index()
{
     var token = await GetBearerToken("http://localhost:6144/", "teste", "123456");

     using (var client = new HttpClient())
     {
         client.DefaultRequestHeaders.Add("Authorization", "Bearer "+ token);

         var response = await client.GetAsync("http://localhost:6144/api/values");

         if (response.IsSuccessStatusCode)
         {
             var data = response.Content.ReadAsAsync<IEnumerable<string>>();

             return Json(data.Result, JsonRequestBehavior.AllowGet);
         }
     }   
}

That all works fine… But I need to use the Web Api in all my actions…
So how can I keep that token (despite getting a new token every request) and how verify if it expired … Is it possible to keep that together with authentication cookie someway?
Any best pratices to deal with that scenario?

Thanks

Best Answer

If I get it right your MVC 5 client app is accessing a WebAPI of a different app. The MVC 5 Client uses a cookie to authenticate the user. To access the WebAPI you get a Bearer tokeen from the /Token endpoint and send it in the Authorization header.

You do not call the WebAPI from your client side Javascript code, you just call it from within MVC Actions running on the server of the MVC5 application.

Getting a new Token before each service call sounds wrong. This would mean 2 roundtrips each time. This can't be performant.

If I got that right, you could:

  1. Store the token in the Session object. For as long as your user of the MVC App is authenticated and his session is alive you would then always have the same Token. If its expired you would get a 401 unauthorized access back from the WebAPI. To keep your MVC Action Unit Testable you could wrap the session access into a Service that you inject into the Action (Dependency Injection).

  2. you could store the Token in a cookie similar to the Authentication cookie already existing. This way you would not need a Session on the server side. Here again I would wrap the access to get the Token from the Cookie in a service that all your actions use.

I would use the Session storage. Simple. Straight forward. But maybe I am missing something

Hope this helps you. Feedback appreciated :-)

Related Topic