Azure WebApp Cors does not add Cors headers - azure

I have an Owin WebAPI2 .NET app that I host on an AppService in Azure.
I want to add CORS support using Azure as in this article. It seems simple, you just add an Origin site to the list like this: http://screencast.com/t/r2ATq4u5
I would now expect the Response headers to contain this allowed Origin.
However, the CORS headers are not included in the Response Headers when I check it with Fiddler:
http://corstestqm.azurewebsites.net/breeze/restaurantsbreeze/basictest
Steps I have tried:
Stripped out all CORS Nuget libraries from my solution and all traces of CORS code in my API project.
Deployed to a brand new AppService
Enabled Owin Cors AllowAll
None of these had any effect. (ie. the Response does not contain the CORS header specified in Azure).
Am I missing something really basic here?
UPDATE
I simplified the problem even more:
In VS2015, I created a new API project and pushed it to http://corstestbasicap2.azurewebsites.net/api/values/
with no changes (ie. it should NOT have CORS enabled).
I then use Test-Cors tool to hit that API. It does not get a CORS error as expected. I then go into Azure and add a dummy URL (e.g http://www.example.com) and try the CORS test again. It should fail as Azure should only let example.com through. However, it works fine.
I then edit CORS again in Azure and add http://www.test-cors.org below http://www.example.com (so it should let either through) and now the headers return Access-Control-Allow-Origin:http://www.test-cors.org as expected.
But this makes no sense? Surely the previous call should fail when "http://www.test-cors.org" was NOT in the allowed Origins? It does not seem to be doing anything useful?!

You can achieve these by adding in your web.config bellow configuration:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,Authorization"/>
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
</customHeaders>
</httpProtocol>
</system.webServer>
In global.asax:
protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
Response.Flush();
}
}
If you want control from portal, please view bellow image:
Note, according with App Service CORS documentation you can not use both Web API CORS and App Service CORS in one API app. You have to clean your project about Web API CORS
Don't try to use both Web API CORS and App Service CORS in one API
app. App Service CORS will take precedence and Web API CORS will have
no effect. For example, if you enable one origin domain in App
Service, and enable all origin domains in your Web API code, your
Azure API app will only accept calls from the domain you specified in
Azure.

My problem was that I accidentally put http instead of https into Azure AD B2C custom page config blade ... After change to https it works like a charm.
CORS headers missing when deployed on Azure Web App / Azure API

Related

.Net Core 3.1 Web API CORS Policy block after adding UseAuthentication() in Startup.cs

I created an ASP.NET Core 3.1 Web API and a Javascript client that calls the Web API methods to get data.
The Web API is secured by an Azure AD app registration to prevent the usage of the API by foreign users or clients. The Web API is currently running on an internal network.
The problem at the moment is that I need to enable CORS in my API. I already got CORS enabled on my API and the Javascript client could get responses from the API but since I added the Azure Authentication with the app.UseAuthentication() method I get CORS errors again
I added following to my Startup.cs ConfigureServices and Configure methods to enable CORS:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddMicrosoftIdentityWebApiAuthentication(Configuration);
services.AddCors(o =>
{
o.AddPolicy("Allow", builder =>
builder.WithOrigins("https://www.example.com")
.AllowAnyMethod()
.AllowAnyHeader());
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseCors("Allow");
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
The services.AddMicrosoftIdentityWebApiAuthentication(COnfiguration) and app.UseAuthentication() are used to enable the authentication with my Azure AD. The properties for this authentication are set in the appsettings.json. This authentication is also already working.
But since I added this authentication with the two mentioned methods, I get CORS policy errors when using the API.
Before I added this two methods everything is working and I don't get CORS errors. While I tested everything I recognized that when I remove the app.UseAuthentication() call from the Configure method, I don't get the CORS errors and my requests coming from my Javascript client has the Access-Control-Allow-Origin header.
When I add app.UseAuthentication(), the header isn't present in my request.
This is the error I currently get:
Access to fetch at 'https://example_XXX.com/api/example/example' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I already tried to add the [EnableCors("Allow")] tag to my controller, but this also did not work.
Maybe anyone of you has an idea what the problem is and why I'm getting this error when I'm adding the app.UseAuthentication() method?
If you think you need any more information about the problem feel free to comment and i will provide. I changed my URLs to examples.
UPDATE:
I recognized that the CORS error only occur when deploying the api and hosting it over IIS. Maybe anyone is familiar with that.

CORS error using passport-azure-ad on React + Express app

I have a React + Express app for which I am using the passport-azure-ad OIDCStrategy, but I'm having trouble with CORS.
The error I am receiving is:
Access to XMLHttpRequest at 'https://login.microsoftonline.com/...' (redirected from '{SERVER_URL}') from origin '{FRONTEND_URL}' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My frontend and backend are on different domains (I added a header on the backend to allow the frontend origin).
I tried adding both urls as Redirect URIs, but that doesn't seem to help.
Is there a way to set Access-Control-Allow-Origin headers in Azure? Or is there a configuration in the React code which I'm missing?
Is there a way to set Access-Control-Allow-Origin headers in Azure?
Or is there a configuration in the React code which I'm missing?
Generally, this error occurs when the front end and backend is running on different ports.
The browser will not accept the responses from the backend because of the CORS headers not present.
So, we have to add the CORS headers in the backend request to overcome this issue by using the cors npm package below:
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
It enables CORS headers with all the requests.
you can refer to cors documentation for more information.
Also, We can enable CORS for Azure App Service in azure portal as mentioned here.
You have to use CORS package in the backend and give CORS access in your domain like
const cors = require('cors')
var corsOptions = {
origin: '*',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(cors(corsOptions));
I want to assume you already set up CORS options in your backend. So, from the error one could see that the frontend is able to access the backend but not able to get access to the 3 party 0auth from Microsoft azure right.
I am sure if you ran both the frontend and backend on the same port it would be successful provided you already set up your azure account to receive requests from your backend end point.
The problem is you running it on different ports, your react app on a particular port and the backend on another port. Then you used fetch in the react app to try and get the backend which will then send requests using the passport-azure to Microsoft.
So instead of using fetch from react to backend to 0auth service, use an anchor tag.
Kindly check out this github issue as this person also encountered this same error
"Fixed. Don't use fetch from react to api to oauth service. Use a link (anchor/location.href) instead and let the flow of the oauth process take over in the browser." - what the issue owner said.
I hope it helps.

Azure App Service (Node) CORS origins won't work no matter where I add them

The Azure CORS settings doesn't seem to work at all unless I specify * any and all requests will return
"has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."
I've added my CORS http + https variants of both my production + dev environment frontend. I have also added them in the web.config.
<add name="Access-Control-Allow-Origin" value="https://LINK"/>
<add name="Access-Control-Allow-Origin" value="https://LINK/"/>
It is becoming extremely unpredictable and unreliable. The application is configured to allow all origins:
app.options('/', function(req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', '*');
res.setHeader('Access-Control-Allow-Headers', '*');
res.end();
});
So it would send preflight data. Does azure CORS not send any preflight data? Am I better off just setting * everywhere and then managing things via the API myself? Will Azure not overwrite that configuration anyway? Am I stuck with no way of managing CORS?
Yes, definitely you can achieve it either by setting CORS headers from the Azure portal or by adding CORS headers from your App.
Here's how you can set it form azure portal.
Navigate to azure portal
Navigate to the app service you have created.
Click on CORS in the app.
Enter URL's in the empty Allowed Origins text box.
Click Save.

Disable CORS middleware of Azure app service

I wrote some code to handle CORS into my Web Api(.Net Core). These code perfectly works on my local and test server(Azure app service) but it is not working on production(Azure app service). It gives error-
XMLHttpRequest cannot load http://myapiproduction.co/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myuidashboard.co' is therefore not allowed access.
I gave correct allowed origin url in appsettings.Production.json. I removed all value (*) from CORS section of Azure app service(Production env).
When we removed every thing from CORS section of app service then our code logic should work because at a time only one middleware will work either app service's CORS middleware or our Web Api code logic.
Web Api (Startup.cs)-
var allowedOriginsArr = Configuration["AppSettings:AllowedOrigins"].Split(','); //Example- "http://myuidashboard.co"
services.AddCors(options =>
{
options.AddPolicy("AllowAllCorsPolicy",
builder => builder.WithOrigins(allowedOriginsArr)
.WithMethods("GET", "POST", "PATCH", "PUT", "DELETE", "OPTIONS")
.AllowAnyHeader()
.WithExposedHeaders("X-Auth-Token")
.AllowCredentials());
});
So, my question is - Is there any other setting i have to do to disable CORS middleware of Azure app service? I want to control CORS completely by code (Api logic).
I don't think there is any extra setting to disable it explicitly from Azure App Service side. Microsoft itself recommend to use your CORS utilities instead of inbuilt one - Refer Here.
Note Provided by Doc -
Don't try to use App Service CORS and your own CORS code together. When used together, App Service CORS takes precedence and your own CORS code has no effect.
Try to check the deployed appsettings.json in the associated appservice using Kudu or command line. Might be the appsettings isn't being applied.
Associated App Service > Under the Development Tools > Advanced Tools (Kudu)
Associated App Service > Under the Development Tools > Console
Don't try to use App Service CORS and your own CORS code together. When used together, App Service CORS takes precedence and your own CORS code has no effect.
Please see below how to correctly configure CORS on ASP.Net core app:
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0
Or you can also specify and AllowAnyOrigin but, it's unsecure configuration and can result in cross-site request forgery.
EDIT
As long as I know there's not available functionality to "disable" CORS in Azure hosted app.
My azure site is programmed in vb.net, but ultimately I had to do this and then it worked:
Dim strMethod As String
strMethod = Request.HttpMethod.ToUpper
If InStr(strMethod, "OPTIONS") Then
Response.Flush()
End If

Azure Mobile Apps receiving webhooks

I need to receive webhook requests in the same backend as my mobile app. They are sent as POST with content-type application/x-www-form-urlencoded. As far as I can tell, I have to use the [MobileAppController] attribute on my controllers, but this forces me to send in a header named "zumo-api-version" (which my webhook provider obviously does not send in the request). Any ideas on how to go about this?
but this forces me to send in a header named "zumo-api-version" (which my webhook provider obviously does not send in the request).
You can opt out of version checking by setting a value of true for the app setting MS_SkipVersionCheck. Specify this either in your web.config or in the Application Settings section of the Azure portal. After setting MS_SkipVersionCheck to true, zumo-api-version header is not required.
<appSettings>
<add key="MS_SkipVersionCheck" value="true"/>
</appSettings>

Resources