CORS policy error with front end and back end all on Azure - azure

We have an Angular web application running on Azure. The backend is Dot Net Core 3.1. The Authentication is done through Azure AD. What is happening is the following steps
User logs into the web site and navigates to a page. Everything is working as expected
The user logs out, but does not close the tab. The Logout screen is shown as expected
The user opens a new tab and navigates to the web site
The user is NOT prompted for a login and when the user navigates to page they get error
Access to XMLHttpRequest at 'https://login.microsoftonline.com/2aa666ca-a53c-4274-bfcc-41b83867d22a/oauth2/authorize?client_id=794424bb-0ad2-41f8-b007-b71ed576b793&redirect_uri=https%3A%2F%2Fmydomain.azurewebsites.net%2Fsignin-oidc&response_type=id_token&scope=openid%20profile&response_mode=form_post&nonce=637782164067215548.NzQ4MWQxNjgtYjdlZS00OTlmLWIwYzctM2NhZWRkZjdhMTZiYzdmNjljOTEtNTk3OS00NDlhLWEzZjgtODZkN2YyZDZmYzlh&state=CfDJ8IE9b1M0cDdJqtQPg1_KxRR0vlYAN1zOfKzhpzhdzqvcX_XGygV8nincOzoVYDPPyZWnbh5SrGMDZhQfmUDlO4wQ41v_7Q_gJCUHftetejZZQZTS7Uhn-IVBRysh36hvldRY2pxcZBKCQHLYkKMnR2my9R0TqsaqEAI4gGNUUHwa8fJnv4xj0lkMJq_DORhJS4AwLMhtQWGvuIp0gzQ_cGR0gjGZvMRMTaBZunGBDexThOzzbAyQJTCJuNxUUB_tvAm0cFEVWb3lTPYRgk1ARnagmg7a6GDFrCnXT7vT_3VJjUyMzrazbt1xeRtrs1AdlUIX1fnnFsGZPGUBA3kYvzTyEgVkm97FGBTPgeGZAP3W&x-client-SKU=ID_NETSTANDARD2_0&x-client-ver=5.5.0.0' (redirected from 'https://mydomain.azurewebsites.net/api/profileTypes?_=1642619606751') from origin 'https://mydomain.azurewebsites.net' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
If the user refreshes the page, then they are forced to login and everything begins working again
I have tried adding in CORS as directed on other questions and other websites as follows
In the ConfigureService function of the startup.cs The following code is present
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder
.WithOrigins(new[] { "http://YOUR_FRONTEND_ORIGIN" })
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}));
In the Configure function of the startup.cs is the following code
app.UseCors("CorsPolicy");
I am confused as to why CORs would even come into play as everything is on the same Azure subscription, but I added the above code and it does not change anything. Searching the internet give mainly the same or similar implementations as above.
I am not sure how to proceed or even what questions to ask, so any help would be appreciated

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism which basically allows server to indicate any origins other than its original url or scheme or domain or port .But cors settings may also vary from different browsers which may cause this error.
In case of Azure App Service it sets “AppServiceAuthSession” cookie for authenticated session with browser. The web application may use XMLHttpRequest / AJAX request inside the app and the request sent may contain the AppServiceAuthSession cookie. When this cookie is still present in the browser and the web page pointing to the page of app may not be the original url and which might be the possible cause of error.When this cookie is not present in the request, Azure App Service will redirect the request to Azure AD for login that is why when you referesh it, it works.
If the browser is enabled with cors ,it makes a pre-flight cors check to the specified url and gets the access-control-allow-origin headers, we can modify this headers accordingly,if origin restriction is not required.
Try to insert the http protocol present in the asp.net Web Api backend, in the Web.config between the <system.webServer> </ system.webServer> tags,
Example:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
and you can try enable access to all origins from browser settings .
Please check this reference access to xmlhttprequest has been blocked by cors policy Code Example (codegrepper.com) if you can enable credentails to true and by using cors variable to use in app.use(cors).
References:
Cross-origin XMLHttpRequest - Chrome Developers
express - Angular CORS request blocked - Stack Overflow

Related

Forms Authentication fails to redirect to Login

I am developing a WebForms project in VS 2017 and I would like to add Forms Authentication so that anonymous users cannot access a specific page (called Resources). So far, my Login page is logging in users as it should, authenticated users have access to Resources, and all users can browse my non-protected pages.
Here's my problem: Whenever an anonymous user attempts to access Resources, a server error occurs instead of being redirected to the Login page. In IIS Express the error message is "HTTP Error 401.0 - Unauthorized. You do not have permission to view this directory or page". In Local IIS it says "Error message 401.2: Unauthorized: Logon failed due to server configuration. Verify that you have permission to view this directory or page based on the credentials you supplied and the authentication methods enabled on the Web server.
I believe the browser and server are trying to authenticate using different methods, but I can't figure out how to fix this.
In IIS manager, I've enabled both forms and anonymous authentication and disabled the other methods for my website. For anonymous auth, I've tried setting the user to IUSR as well as Application pool identity while running on DefaultAppPool with full security permissions - neither worked. And for Forms auth, the parameters match my web.config file, aka same name and login url (not sure if that matters).
Here is the authentication and authorization code in my web.config:
<authentication mode="Forms">
<forms name=".ASPXAUTH" defaultUrl="Index.aspx" loginUrl="Login.aspx" />
</authentication>
</system.web>
<location path="Resources.aspx">
<system.web>
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
</system.web>
</location>
Am I missing something obvious? Are there other settings I should check out? Any help is immensely appreciated!

Remove Server:HTTPAPI/2.0 header on invalid request

I'm trying to stop MS Azure responding with the header/value of Server: HTTPAPI/2.0 on receipt of an invalid request, for example an invalid hostname.
I've seen this SO entry...
Removing Server and X-Powered-By HTTP Headers on Azure Web Site Preview
..and one answer suggests that the only way to get around this is to host the website on an Azure VM, something I'd much rather avoid.
It's 3.5 years on from that question/answer - does anyone know if it can now be suppressed in a WebApp solution
According the description at Remove standard server headers in Azure Web Sites:
HTTP headers are part of the communication process between web servers and browsers, and are included in the request and response. One example is the server header, which lists the product name and version of the web server (e.g., Microsoft-IIS/8.0). All web servers generate these headers, but now you can disable them on Azure Web Sites.
You can try to modify or create a new web.config in the root directory of your application on Azure Web Apps, with following content:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<security>
<requestFiltering removeServerHeader="true" />
</security>
</system.webServer>
</configuration>
Please refer to https://azure.microsoft.com/en-us/blog/removing-standard-server-headers-on-windows-azure-web-sites/ for more info.
To remove the MVC header, add this in Global.asax - Application Start event:
MvcHandler.DisableMvcResponseHeader = true;
Using this will remove the version headers,
<httpRuntime enableVersionHeader="false" />

The provided anti-forgery token was meant for user "UserName", but the current user is ""

When I am login with user's credential, first time no error while login to application,
but when I logoff and again login with other user's credential got an error
The provided anti-forgery token was meant for user "UserName", but the current user is "".
I am implementing AntiForgoryToken and IPrincipal with asp.net mvc 5
I tried :
AntiForgeryConfig.SuppressIdentityHeuristicChecks = true; in Application_Start()
I already refered this link When attempt logoff, The provided anti-forgery token was meant for user "XXXX", but the current user is ""
How can I fix this error ?
Thanks in advance.
I found my IIS instance had both Anonymous and Windows authentication enabled which was causing this exception for my application
Authentication Settings both enabled
This setting seems to be the cause of this exception. It seems that the ValidateAntiForgeryToken action filter was using the current user populated with an empty string in the Anon authentication and then attempting to match it against the token which was populated using Win authentication.
By turning off either Windows or Anonymous authentication (for my application I switched off Anon authentication,) the tokens now match up.
Authentication Settings one enabled
This setting can be altered in IIS manager or in the web.config file like so
<system.webServer>
<security>
<authentication>
<anonymousAuthentication enabled="false" />
<windowsAuthentication enabled="true" />
</authentication>
</security>
</system.webServer>
You don't really need to check for the antiforgery token on the post method of your login.
Antiforgery tokens provide protection from CSRF attacks. A CSRF attack happens when a malicious script/link posts an HTTP request on your behalf without your knowledge or consent. When an antiforgery token is embedded on your page, the server can check for this token when it receives the request to verify that the request indeed came from the page. A request from a malicious script or link will not have the token and will fail.
So, all other post actions that you want to protect should be decorated them with the [Authorize] and [ValidateAntiForgeryToken] attributes. The login post method, however, doesn't need either of these attributes.
Update: It is really needed. See answer in Stephen Muecke's comment.

CORS Preflight request not working with Azure API Management

I have 2 Azure Websites (ASP.NET MVC 5 and ASP.NET WebApi 2). The MVC website has some jQuery which tries to post CORS request to the WebApi. It works just fine if it connects directly to the WebApi. However it doesn't work when trying to connect through the API Management.
The error I got in Chrome is:
XMLHttpRequest cannot load https://XXXXXX.azure-api.net/api/search. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://YYYYYY.azurewebsites.net' is therefore not allowed access.
I ruled out the problem being with the WebApi config, because as I said it works directly.
Below is my policy:
<policies>
<inbound>
<cors>
<allowed-origins>
<origin>*</origin>
<!-- allow any -->
</allowed-origins>
<allowed-headers>
<header>accept</header>
<header>accept-encoding</header>
<header>access-control-request-headers</header>
<header>access-control-request-method</header>
<header>connection</header>
<header>content-type</header>
<header>host</header>
<header>origin</header>
<header>referer</header>
<header>user-agent</header>
</allowed-headers>
<expose-headers>
<header>access-control-allow-headers</header>
<header>access-control-allow-origin</header>
<header>cache-control</header>
<header>content-length</header>
<header>date</header>
<header>expires</header>
<header>pragma</header>
<header>server</header>
<header>set-cookie</header>
<header>x-aspnet-version</header>
<header>x-powered-by</header>
</expose-headers>
</cors>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
</policies>
Any ideas?
CORS policy intended use is for the cases when your backend does not support CORS. In that case you can put this policy in and it will reply to OPTION requests without forwarding them to your backend. And you can use this policy to decide which origins/headers/methods to process for CORS.
Alternatively, if your backend already supports CORS and you see no benefit in handling CORS flow on APIM level you could just proxy the entire flow. For that to happen you should remove CORS policy and create a new operation in your API in APIM with OPTIONS method, so that OPTIONS requests would be forwarded to backend normally.
After spending many weeks fighting this issue, and coming up empty, I (with the help of Microsoft Support) discovered a bug in Azure API Management. If you have multiple APIs and one of them does not have an URL suffix (even if it's not the one that's failing), check it's CORS policy. The first API we put in Azure API Management didn't have any methods other than GET, so we set a CORS policy to only allow GET and OPTION. However, the bug that exists seems to make all inbound pre-flight requests route to the API without an URL suffix. So I was able to fix my issue by added a PUT (and POST for good measure) to the CORS policy of an unrelated API.
TL;DR: Check to make sure the CORS policy of the API with no URL suffix allows the method that's failing.
Hope this saves someone's sanity.
I was getting below preflight error from APIM and found that issue is that my policy <method>*</method> is actually not working. Changing the policy to explicitly add all the HTTP Verbs like below has resolved my issue.
<allowed-methods preflight-result-max-age="300">
<method>OPTIONS</method>
<method>GET</method>
<method>POST</method>
<method>PUT</method>
<method>PATCH</method>
<method>DELETE</method>
</allowed-methods>

Azure API App adds extra Access-Control-Allow-Origin header

It appears that when deploying an web app as an Azure API App, it adds an extra Access-Control-Allow-Origin: * header to the response. How can I override and remove this?
My project uses SignalR and OWIN, when I add or change the Access-Control-Allow-Origin through the requests or setup in my own code, I get to specify another Access-Control-Allow-Origin header property, but the additional wildcard (*) header is always added as well.
This makes my requests to SignalR fail, as it includes authentication header which is not allowed when origin is *.
API Apps are hosted behind the "API app host", I presume that is the origin of this additional header. Is there any way I can modify this behavior?
Note: the additional header is NOT present when deployed as a regular Azure Web App.
this may be because you have the MS_CrossDomainOrigins app setting set in addition to having CORS enabled in your backend. If so, please remove one or the other.
Thanks.
Watch out do not have set up in your web.config something like this:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
Delete it if it exists.

Resources