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