Authentication in .NET Web API using MVC FormsAuth

2019-04-10 00:25发布

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

XmlHttpRequest

Screenshot of fiddler when request is done directly in the browser Directly in the browser

Screenshot of a authentication controller to test Authentication controller

1条回答
The star\"
2楼-- · 2019-04-10 01:10

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.

查看更多
登录 后发表回答