Ive managed to enable Cors fine and my client application communications to my web API application using AJAX. The problem is its open to any host now. I added the following line to Startup.Auth.cs:
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
I was using the standard WebApi method for cors, but had problems when issuing token authentication.
My question is how do i restrict origins using this method?
You can restrict the origin using CorsPolicyBuilder Class
app.UseCors(builder =>
builder.WithOrigins("http://localhost", "https://localhost"));
Define one or more named CORS policies, and then select the policy by name at run time
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.WithOrigins("http://example.com"));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
// Shows UseCors with named policy.
app.UseCors("AllowSpecificOrigin");
...
}
You can read how to define CORS at here.
Related
Working on an app with signalr, managed to solve the cors error with the connection to the API but when trying to connecto to the hub it shows the error below which won't happen when debugging on my local computer even with different port.
Access to fetch at 'http://iisServer:10079/fareg/signalr/negotiate?negotiateVersion=1' from origin 'http://iisServer' 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 an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Here is my configuration on the app
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddSignalR();//.AddMessagePackProtocol();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//add Windows authentication for http options request
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
services.AddDbContext<FAContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("FADB")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(options =>
{
//options.WithOrigins("http://schi-iis1zsus", "http://localhost:4200");
options.AllowAnyOrigin();
options.AllowAnyMethod();
options.AllowAnyHeader();
options.AllowCredentials();
});
app.UseSignalR(routes =>
{
routes.MapHub<Hubs.HubFA>("/signalr");
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
Please help, I've looking every where but haven't get a solution to this issue.
https://learn.microsoft.com/aspnet/core/signalr/security?view=aspnetcore-5.0#cross-origin-resource-sharing
You either need to specify the origins explicitly, or remove AllowCredentials() and set withCredentials to false on the client https://learn.microsoft.com/aspnet/core/signalr/configuration?view=aspnetcore-5.0&tabs=javascript#configure-additional-options-1
I have a .NET core web api. It works as expected when requesting from Postman but returning
Status Code: 500 Internal Server Error
Referrer Policy: strict-origin-when-cross-origin
when requested from other React JS client. I have already enabled CORS in the Startup.cs like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
...
}
But still getting the Status Code: 500 Internal Server Error. I have been trying to solve this issue for too long. Please help. Thanks.
add this in your configure method:
// global cors policy
app.UseCors(x => x
.SetIsOriginAllowed(origin => true)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
if its not solved then add a custom middleware and check your request you can use ilogger for logging exception.
follow this link for middleware: https://www.tutorialsteacher.com/core/how-to-add-custom-middleware-aspnet-core
I want to develop a reverse proxy in .net core api and I want to use subdomains to route requests to different services. Subdomains are not specified already rather it will be processed dynamically
I have tried to use the following CORS policy
but my middlewares does not capture any request coming through subdomains rather only handle which are coming from http://www.localproxy.com
namespace OrchestratorReverseProxy
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddCors
(
options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.SetIsOriginAllowedToAllowWildcardSubdomains()
.WithOrigins("http://*.localproxy.com")
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyHeader()
.Build()
);
}
);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("CorsPolicy");
app.UseMiddleware<DarkLaunchMiddleware>();
app.UseMiddleware<ReverseProxyMiddleware>();
}
}
}
The browser shows response like
This site can’t be reached www.the.localproxy.com’s server IP address could not be found.
Try running Windows Network Diagnostics.
DNS_PROBE_FINISHED_NXDOMAIN
I have just moved my code to our QA environment which uses https and what was working in Dev is not working in QA because the browser gets stuck in an infinite redirect loop. Our load balancer forces https so when the login redirect happens from code, which for some reason it's trying to redirect to http instead of https, the load balancer is stopping it and adding https again which causes the infinite loop. The question I have is why is this code not just redirecting to https, the path is relative in the ConfigureServices() method. I've looked at it in fiddler, and it is indeed adding the FQDN for the redirect with http instead of https.
Is there some property I need to add to options here to allow https redirects?
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/LogIn";
options.LogoutPath = "/Account/LogOff";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
}
thanks.
We just use:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
... //settings and logging initialization
app.Use((context, next) =>
{
context.Request.Scheme = "https";
return next();
});
... //all the rest middleware calls
}
and it helps in most situations under OWIN and .Net Core up to 2.0
Based on #Programmer's suggestion in the comments to the OP, I took a look at this: https://codeopinion.com/configuring-asp-net-core-behind-a-load-balancer/ It describes my situation exactly (ssl termination at the load balancer and the .net core 2.0 app redirecting to http for login). I then tried making the request through the LB with the header the article suggests and adding in the Configure() method of the Startup class this piece of code:
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedProto
});
what was interesting is that when I made a request including the proto header:
X-Forwarded-Proto:https
from outside the LB, it passed that header through to the app and it worked great, no more infinite redirect loop. However when our infrastructure guys added that header to the request that the LB makes to the internal nodes behind the LB, I was getting a redirect to https, yay, but it was also prepending the ip address to the redirect URL (we have a netscaler LB). Apparently by default when you add a custom header, there's a checkbox to include the IP to the internal node and that had to be unchecked. After that was done, we're in business.
thanks again #Programmer for your help. You definitely pointed me in the right direction.
For .net core 2.1 and up with azure authentication try this code.
services.Configure(AzureADDefaults.CookieScheme, options =>
{
options.Cookie.SameSite = SameSiteMode.None;
});
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => Configuration.Bind("AzureAd", options));
I have .Net Core application with angular 2 cli. I am trying to call my controller action from the different port, I know that I can use CORS to make that work, but it is not working. has anyone the idea what could be the problem? thank you!
Your current configuration is allowing the wrong origin (HTTPS and not HTTP).
//Optional - called before the Configure method by the runtime
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors(builder =>
{
builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader();
});
)
}