I have created an api using .net core 5.0 but no matter what I do it seems to block my request to it giving the error
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
my code in my startup.cs is
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(options =>
{
options.AddPolicy("AllowAnyCorsPolicy", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
});
services.AddTransient<IChatLog, LogsData>(provider => new LogsData());
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
From what I have read that should allow any requests from anywhere, but for some reason it is still blocking.
Has anyone any idea what is wrong?
Because app.UseCors() did not specify a policy name. You can add the name AllowAnyCorsPolicy.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
app.UseCors("AllowAnyCorsPolicy");
//...
}
Use this syntax:
services.AddCors(o => o.AddPolicy("AllowAnyCorsPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
and this too:
app.UseCors("AllowAnyCorsPolicy");
Related
I am trying to implement google authentication in asp.net 5 and getting error
Exception: The oauth state was missing or invalid.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ManualDataMiningManagerContext>(
options => options.UseSqlServer("name=ConnectionStrings:DBconnection"));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddDefaultUI()
.AddEntityFrameworkStores<ManualDataMiningManagerContext>()
.AddDefaultTokenProviders();
services.AddRazorPages();
services.AddControllersWithViews();
services.AddAuthentication()
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddGoogle(options =>
{
IConfigurationSection googleAuthNSection =
Configuration.GetSection("Authentication:Google");
options.ClientId = googleAuthNSection["ClientId"];
options.ClientSecret = googleAuthNSection["ClientSecret"];
options.SignInScheme = IdentityConstants.ExternalScheme;
});
services.ConfigureExternalCookie(options => { options.Cookie.SameSite = SameSiteMode.None; });
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseForwardedHeaders();
app.UseHsts();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseForwardedHeaders();
//The default HSTS value is 30 days.You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapDefaultControllerRoute();
});
}
my startup class method attached. am I missing anything?
and one more thing this app deployed on subdomain looks like operation-done.abc.com
I have a Blazor server side app that uses authentication. I tried Azure SignalR as suggested by Visual Studio but after that when I am not authenticated I get a blank page instead of the typical not authorized webpage.
If I check the browser debug console, the following message appears:
"Error: Failed to complete negotiation with the server: Error: Unauthorized"
It looks this message is thrown by signalR.
If I change the line endpoints.MapBlazorHub().RequireAuthorization(); to endpoints.MapBlazorHub() in the startup.cs file, it runs as expected.
Any idea on how to fix this?
I tried rolling back the changes made by VS, but it still doesn't work as before.
Thank you
Edit 1: This is the app.cs code for your review:
<CascadingAuthenticationState>
<Router AppAssembly="#typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="#routeData" DefaultLayout="#typeof(MainLayout)">
<NotAuthorized>
<h1>Restricted Access</h1>
</NotAuthorized>
</AuthorizeRouteView>
</Found>
<NotFound>
<LayoutView Layout="#typeof(MainLayout)">
<p>Page not found</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
Edit 2:
This is the startup class
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// 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.AddDbContext<IdentityBDContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("IdentityBD"),
providerOptions => providerOptions.EnableRetryOnFailure()));
services.AddIdentity<CustomUser, IdentityRole>(options =>
{
options.User.RequireUniqueEmail = true;
options.SignIn.RequireConfirmedEmail = true; //prevents registered users from logging in until their email is confirmed.
}).AddRoles<IdentityRole>()
.AddEntityFrameworkStores<IdentityBDContext>()
.AddDefaultTokenProviders()
.AddUserManager<ERPUserManager>()
.AddSignInManager<ERPSignInManager>();
services.AddAuthorization(options =>
{
options.AddPolicy(SD.Admin, policy => policy.RequireRole(SD.Admin));
options.AddPolicy(SD.POS, policy => policy.RequireRole(SD.POS, SD.Admin));
options.AddPolicy(SD.AllowedTenant, policy => policy.Requirements.Add(new AllowedTenantRequirement(21)));
options.AddPolicy(SD.SysAdmin, policy => policy.RequireRole(SD.SysAdmin));
});
services.AddRazorPages(options =>
{
options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
});
services.AddServerSideBlazor();
//services.AddSignalR().AddAzureSignalR();
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<CustomUser>>();
services.AddTransient<ConfigService>();
services.AddTransient<IdentityService>();
services.AddTransient<TenantService>();
services.AddHostedService<TimerUpdate>();
services.AddScoped<IAuthorizationHandler, AllowedTenantHandler>();
//Delete in production
services.AddServerSideBlazor().AddCircuitOptions(options => { options.DetailedErrors = true; });
services.AddScoped<ITenantProvider, WebTenantProvider>();
services.AddDbContext<ERPContext>(options => options
//.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddConsole()))
.UseSqlServer(
Configuration.GetConnectionString("ERPDB")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<IdentityBDContext>();
context.Database.Migrate();
}
// Workaround for https://github.com/aspnet/AspNetCore/issues/13470
app.Use((context, next) =>
{
context.Features.Get<IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = null;
return next.Invoke();
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub().RequireAuthorization();
endpoints.MapControllerRoute("mvc", "{controller}/{action}");
endpoints.MapFallbackToPage("/_Host");
});
}
}
I'm experiencing some difficulties with CORS in angular 11 and Asp.net Core 2.1.1. The Angular server running on port 4201, the Asp.net Core server on port 8990. I always get an error like this
Access to XMLHttpRequest at 'http://10.31.80.108:8990/api/localization/login' from origin 'http://10.31.80.108:4201' 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.
although I have enabled CORS in the Startup.cs file:
app.UseCors(builder => builder.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins(new []{ "http://10.31.80.108", "http://10.31.80.108:4201"})
//.WithOrigins(origins.ToArray())
.AllowCredentials());
I've tried different variations that should allow all requests, but it doesn't work in Angular. Can anyone suggest a possible solution?
Here is most of the Startup file:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
...
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddMemoryCache();
// services.AddCors();
services.AddCors(o => o.AddPolicy("AllowAnyOrigin", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
})); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo(Configuration["CultureOptions:DefaultCulture"]);
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(Configuration["CultureOptions:DefaultCulture"]);
var cultureOptions = new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture(new CultureInfo(Configuration["CultureOptions:DefaultCulture"])),
};
var configCultures = Configuration.GetSection("CultureOptions:SupportedCultures").GetChildren();
configCultures.ForEach(config =>
{
cultureOptions.SupportedCultures.Add(new CultureInfo(config.Value));
cultureOptions.SupportedUICultures.Add(new CultureInfo(config.Value));
});
app.UseRequestLocalization(cultureOptions);
List<string> origins = Configuration.GetSection("Origins:value").Get<List<string>>();
app.UseCors("AllowAnyOrigin");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// https://joonasw.net/view/hsts-in-aspnet-core
app.UseHsts();
}
app.UseAuthentication();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
});
}
you have a wrong syntax. try this
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("AllowAnyOrigins", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
.....
app.UseRouting();
app.UseCors("AllowAnyOrigins");
//app.UseAuthorization();
}
if it works replace AllowAnyOrigin() with yours
.WithOrigins ("http://10.31.80.108", "http://10.31.80.108:4201");
I have an application written in Angular 10 and Angular Material talking to my backend in ASP.Net on the same server but different port.
For example: (Angular Front End) http://something.com:5000 --> (ASP Back End) http://something.com:5100
I am getting blocked by CORS unless I use the MOESIF CORS Extension.
I am adding the 'DisableCors' tag to each method in ASP like so:
[HttpGet("Travelers")]
[DisableCors]
public IEnumerable<PDox_Trav> Get_Trav()
In my 'Startup.cs' I have this:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => {
options.AddDefaultPolicy(builder => {
builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
});
});
services.AddControllers();
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
What am I missing? Do I need something in my Frontend too? I did not think I did...
I am adding cors as bellow.I used this method in few project and it worked.
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("http://localhost:5000","http://localhost:4200");
}));
Hello I'm trying to migrate a .Net Framework 4.6 application to asp.net core 2.2 and I'm block on the HttpContext.Session use.
I can call the SetString method, but on the second request the GetString return always null value.
I tried different answers found on Stackoverflow and official documentation but none of them are working on my case
public void ConfigureServices(IServiceCollection services)
{
var appConfiguration = new AppConfigurationManager(Configuration);
var allowedOrigins = appConfiguration.AllowedOrigins.Split(',').Select(s => s.Trim()).ToArray();
services.AddSingleton(Configuration); // Config
services.AddCors(o => o.AddPolicy("default", builder =>
{
builder.WithOrigins(allowedOrigins)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
})); // CORS
TokenVerifier.ControlToken(services, "secretToken");
services.AddSignalR();
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddDistributedMemoryCache();
services.AddMvc().AddSessionStateTempDataProvider();
services.AddSession(options =>
{
options.Cookie.Name = "MySession";
options.IdleTimeout = TimeSpan.FromDays(1);
});
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
...
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseCors("default");
//app.UseHttpsRedirection();
app.UseAuthentication();
app.UseSignalR(routes =>
{
routes.MapHub<MindHub>("/myapp");
});
app.UseMiddleware<ExceptionMiddleware>();
app.UseSession();
app.UseMvc();
}
Note that JWT Authentication, CORS and Signalr are working (maybe helpfull for some of you)
Here is my final working sample code maybe usefull for some of you.
Note than the order is very important.
// 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)
{
string[] allowedOrigins = new string[]; // put your allowed origins here
services.AddSingleton(Configuration); // Config
services.AddCors(o => o.AddPolicy("default", builder =>
{
builder.WithOrigins(allowedOrigins)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}));
TokenVerifier.ControlToken(services, "secretToken");
services.AddSignalR();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.Configure<FormOptions>(x =>
{
x.ValueLengthLimit = int.MaxValue;
x.MultipartBodyLengthLimit = long.MaxValue; // In case of multipart
});
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); // HttpContext into ASP.NET Core
// Register your stuff here
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseCors("default");
app.UseAuthentication();
app.UseSignalR(routes =>
{
routes.MapHub<YourHub>("/hubName");
});
app.UseMiddleware<ExceptionMiddleware>();
app.UseHttpsRedirection();
app.UseMvc();
}