Authentication in .NET Web API using MVC FormsAuthentication

那年仲夏 提交于 2019-12-06 04:17:27

问题


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.



来源:https://stackoverflow.com/questions/15902409/authentication-in-net-web-api-using-mvc-formsauthentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!