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
Related
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.
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.
I am looking for Integration of DocuSignApi with Angular. I am following these steps.
Angular Application
Backend Server using .net core Web API to handle and DocuSign api using nuget.
Can I achieve this?
Option 1 - Angular application - will hit - login method of middleware api application - middleware will communicate - docusign - after successful it will share details of logged in users.
Option 2 - Angular application - directly hit to docusign methods for this When I am doing like this
var url = "https://account-d.docusign.com/oauth/auth?response_type=token&scope=signature&client_id=XXXXXXXXXXXXXXX-01caXXXXXXXX&state=a39fh23hnf23&redirect_uri=http://localhost:81/";
return this._dataService.getThirdParty1(url, header)
.pipe(map((response: Response) => {
return response;
}));
- public getThirdParty(url) {
return this._httpClient.get( url).pipe().pipe(map(this.handleResponse)).pipe(catchError(this.handleError.bind(this)));
}
I am getting error
Access to XMLHttpRequest at 'https://account-d.docusign.com/oauth/auth?response_type=token&scope=signature&client_id=XXXXXXXXXXXXXXX-01ca8f1b220&state=a39fh23hnf23&redirect_uri=http://localhost:81/' from origin 'http://localhost:81' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
account-d.docusign.com/oauth/auth?response_type=token&scope=signature&client_id=XXXXXXXXXX-411a-9bb9-01ca8f1b220&state=a39fh23hnf23&redirect_uri=http://localhost:81/:1 Failed to load resource: net::ERR_FAILED
Please provide a way to check these options.
First, your issue is that you are making client-side calls to DocuSign from a different domain which validated CORS policy which is a security concern.
(Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading of resources. CORS also relies on a mechanism by which browsers make a "preflight" request to the server hosting the cross-origin resource, in order to check that the server will permit the actual request. In that preflight, the browser sends headers that indicate the HTTP method and headers that will be used in the actual request.)
Larry wrote extensively on this topic and here are some of the resources that can help.
Here is a three part series on the topic - https://www.docusign.com/blog/dsdev-building-single-page-applications-with-docusign-and-cors-part-1
Here is his code in GitHub showing you how to create a CORS gateway - https://github.com/docusign/blog-create-a-CORS-gateway
One other useful resource - https://www.cdata.com/kb/tech/docusign-odata-angularjs.rst
I have created a Servive Provider with SAML2 Web SSO.
I have a application with Node JS server and React Js Front End running on separate port 3000 (node) and 3001 (react).
There is a route "http://localhost:3000/app/login " on node that redirect to sso login page if the user is not authenticated (authentication managed by cookies).
But if I tried to invoke the api from the frontend the I am getting the CORS issue as following:
Access to fetch at 'Here' (redirected from 'http://localhost:3000/app') from origin 'http://localhost:3001' 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 tried this solution also but no success.
I got this error in web my web-application which uses express as framewok
then I installed cors package available in npm cors node.js
and used it in my server side script.
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
Seems to be you are getting the issue while trying to access the /samlsso. To enable org.apache.catalina.filters.CorsFilter filter in repository/conf/tomcat/carbon/WEB-INF/web.xml file, as mentioned in Tomcat documentation
If you want to enable CORS headers for any other web app hosted in the Identity Server (such as /authenticationendpoint or /oauth2) you have to do the same in the web.xml files (in case of the authentication endpoint web application, the path is repository/deployment/server/webapps/authenticationendpoint/WEB-INF/web.xml) of those web apps as well.
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