Currently, I have an MVC web application that sells widgets. A user logs into our system using forms authentication, and can then do various functions based on the group th
Is there a way to pass the Forms Auth credentials from our MVC app to our Web api app?
Sure, let's take for example the following MVC controller action calling the Web API:
[Authorize]
public ActionResult CallWebApi()
{
var baseAddress = new Uri("https://example.com");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName].Value;
cookieContainer.Add(baseAddress, new Cookie(FormsAuthentication.FormsCookieName, authCookie));
var result = client.GetAsync("/api/values").Result;
result.EnsureSuccessStatusCode();
// now you can read the result.Content ...
}
}
This assumes that you have also enabled forms authentication in the web.config of your Web API project and that the cookie name is the same as the one used in your MVC project.