Authentication in .NET Web API using MVC FormsAuth

2019-04-10 00:58发布

问题:

We have a single page application using the AngularJS framework that needs to talk to a API implemented in .NET Web API on a different domain.

The problem

The API is implemented in .NET Web API. To authenticate a user for access to our API we implemented the MVC Single Page Application template. This uses FormsAuthentication to grant acccess to the API.

We used Fiddler to debug. When we visited a controller on the API that required authentication directly in the browser we could confirm that the user was indeed authenticated. When we did a XMLHttpRequest, as suspected, no authentication cookies were sent in the headers.

What we would like to accomplish is to use FormsAuthentication to access the .NET Web API hopefully through XMLHttpRequests.

One proposed solution to this was to share sessions between the .NET Web API and the MVC. How can we easily maintain state between the .NET Web API and the MVC part of the project?

It's not very RESTful, we know, but we need a quick solution to this problem.

PS! The FormsAuthentication works with the .NET Web API controllers by using the [Authorize] attribute. It's only that the controllers can't be accesed with XMLHttpRequests.

Screenshot of fiddler when using XMLHttpRequest

Screenshot of fiddler when request is done directly in the browser

Screenshot of a authentication controller to test

回答1:

This is a CORS request. You can use Microsoft.AspNet.WebApi.Cors library.

It's just need add ONE line at webapi config to use CORS in ASP.NET WEB API:

config.EnableCors("*","*","*");

View this for detail.