asp.net-mvcasp.net-coreadfssustainsys-saml2single-spa-react

CORS Error when trying to authenticate using ADFS on asp.net core 3 spa


I have an application built with ASP.NET Core 3, with a react SPA (the application has a useSpa for the react app and the backend is the BL of the application).

Currently the application authentication is Windows authentication, but I want to replace it with ADFS (on premises) authentication. I’m using the Sustainsys.Saml2 package for it. I’ve managed to configure it using addAuthentication and then addSaml2 for the ADFS saml request. But when the browser makes the request for the adfs server it throws CORS error: Access to XMLHttpRequest at '<adfs_server>/?SAMLRequest=…' (redirected from '<my-server/api/endpoint>') from origin '<adfs_server>' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

To investigate the error, I used fiddler to intercept the communication and added manually the 'Access-Control-Allow-Origin': "*" header, and it indeed fixed the error (the problem is I can't change the adfs server, it's not my server).

(All this code is in the Startup.cs of the c# app not in the react app, because I’m using the useSpa with the asp.net core app)

I’ve tried to allow CORS using

     .SetIsOriginAllowed(origin => true)
     .AllowAnyMethod()
     .AllowAnyHeader()
     .AllowCredentials());

I tried to specify the adfs server only (using WithOrigins("https://<adfs_server>")) instead of any origin but after it didn’t help I’ve tried to allow everything I can, but it didn’t help. The CORS error still persists. When I’m searching for this error I see that the problem is with the backend (i.e. the ADFS server), but I can’t change the adfs settings only my Relying trust party settings, and I’m sure that the solution isn’t changing the adfs global settings to allow CORS, because other apps using this adfs server doesn’t need this setting.

I tried to use the AddOpenIdConnect or AddWsFederation, in order to check if the adfs server will respond differntly in other protocols (OAuth2, WS-Federation), but it didn't help. I get the same error.


Solution

  • It looks like you are trying to do the SAML2 handshake from the SPA using XmlHttpRequest. That's not support. You need to redirect the entire browser window to the ADFS and let it redirect back to the Asp.Net Server side which will result in a session cookie on your backend. Once the session is established you can redirect back to your SPA.