Sustainsys / Saml2

Saml2 Authentication services for ASP.NET
Other
940 stars 606 forks source link

Angular + .NET Web API : CORS Error #1424

Closed innotech-banha closed 4 months ago

innotech-banha commented 6 months ago

Hi,

We're using the package Sustainsys.Saml2.AspNetCore2 (version 2.9.2) for .NET 6.

We have successfully gotten the package to work, authenticating and authorizing a user to access our web API when accessing the API directly via the browser. Now we're trying to get an Angular application to connect to the API, and still perform the authentication. For now, both applications are running on localhost, each on its own port.

We're running the Angular application on a Chrome browser and we have this extension installed to add CORS headers to the request.

Without the extension we would get an error saying that the "Access-Control-Allow-Origin" header was missing. With it, we get an error saying that the value of this header is different from the supplied origin. What we noticed is that in the request headers the "Origin" is set to null on the call to the Identity Provider. The Identity Provider is hosted on https://login.microsoftonline.com (Azure AD). We believe that it might be the change in the host name (from localhost to login.microsoftonline.com) that is causing the browser to set the "Origin" to null.

Is it possible to configure the API with Sustainsys.Saml2 in a way that this "Origin" header is filled with the correct origin, in order to avoid this CORS issue?

AndersAbel commented 5 months ago

For Saml2 to work correctly from a single page application you need to let the server side handle the Saml2 handshake. Create an action/API that initiates the flow (calls or returns Challenge). Then redirect the browser to that endpoint. When the authentication is all done it results in a cookie being set on the server side. From there on you either need to use the cookie based session (recommended) or create and hand over an access token (not recommended) to the SPA.

The current recommendation for browser based applications is to use the Backend For Frontend (BFF) pattern. That lets the SPA use the session cookie for authenticating the calls.