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");
}));
Related
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 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");
I am trying to host a remote SignalR hub. I created a .NET core 3.1 web api application where I have following code in my Startup class.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(options => options.AddPolicy("CorsPolicy",
builder =>
{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.AllowAnyOrigin();
}));
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseStaticFiles();
app.UseCors("CorsPolicy");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<KappHub>("/myHub");
});
}
CORS should be enabled to accept every origin. In this project, I created a static index.html file.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h1>Kapp Folc Local Tester</h1>
<script src="js/signalr/dist/browser/signalr.js"></script>
<script>
var connection = new signalR.HubConnectionBuilder().withUrl("/myHub").build();
connection.start().then(function () {
console.log('OK');
}).catch(function (err) {
console.log(err);
});
</script>
</body>
</html>
This works fine! when I dive into developer tools, I can see my web page posting to https://localhost:5001/myHub/negotiate?negotiateVersion=1 and I'm getting a 200 response back. SignalR works great here!
When I use postman or any other REST client, to post to https://localhost:5001/myHub/negotiate?negotiateVersion=1, it works fine and I get a response.
Now I create a second .NET core web api project, also containing a static index.html file, together with signalr.js script. This project however, is not hosting a SignalRhub, but I'm trying to connect to the signalR hub from my first project instead. The index.html is an exact copy of the html from my first project, but with a connection string to the signalR hub from my first project. It looks like this:
var connection = new signalR.HubConnectionBuilder().withUrl("https://localhost:5101/myHub").build();
The startup in my second project looks like this:
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseStaticFiles();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
When I run this project and I navigate to the index.html from my second project, it's unable to connect to the signalR hub from my first project. In developer tools, I get a "(failed)net::ERR_FAILED" status back without any other information.
The examples above are using SSL (https). Also when running both solutions in http mode, I experience the same problem.
Set your CORS like this:
services.AddCors(options => options.AddPolicy("CorsPolicy",
builder =>
{
builder
.WithOrigins("https://localhost:44339/")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetIsOriginAllowed((host) => true);
}));
Note that the order!
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();
}
in our current setup we have a known path for logging in.
But now that we are using core 2.2 I cannot fix the current problem; That is always using loginPath: /Identity/Account/Login but we would like to change this.
Reading a lot on StackOverflow and others, I cannot seem to fix it.
So now i have a complete new MVC app trying to figure out what I am doing wrong.
In my startup I have:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<IdentityUser, IdentityRole>()
// .AddDefaultUI()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = new PathString("/Account/Login2");
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// 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
{
app.UseExceptionHandler("/Home/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.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
What am I doing wrong? Better yet; what is the solution :)
so as it turns out;
I needed to scaffold an identity item (like login) and in the login razor page (login.cshtml) you can add:
#page "~/account/login2"
this is probably also you can fix with the routing in razor during startup:
.AddRazorPagesOptions(options => {...});
haven't tried it out yet, but that is something else..
cheers