The CORS error occurred on SignalR negotiation phase - asp.net

I have the following error in Console after migration from Asp.net core 2.2 to 3.1
Access to XMLHttpRequest at 'someuri/negotiate?negotiateVersion=1' from
origin 'http://localhost:4208'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested
resource.
And the following SignalR configuration:
app.UseCors(Constants.Policy);
app.UseAuthentication();
app.UseEndpoints(
endpoints =>
{
endpoints.MapHub<SomeHub>("/ws/someuri");
});
I've added the following policy:
options.AddPolicy(Constants.Policy,
p =>
p.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithOrigins("http://localhost:4208"));
But it didn't help.

You should configure the CORS this way and the order is important!
On your configure method:
public override void Configure(IApplicationBuilder app, HostConfiguration hostConfiguration, ILogger<Startup> logger)
{
base.Configure(app, hostConfiguration, logger);
app.UseWebSockets();
app.UseCors(CorsPolicy); // first configure CORS, then map Hub
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<SomeHub>("/someuri");
});
}
Then when adding CORS:
/// <summary>
/// Adds the CORS.
/// </summary>
private void AddCors(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(CorsPolicy, builder => builder.WithOrigins("http://localhost:4208")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetIsOriginAllowed((host) => true));
});
}
You can see more detailed answer here.

Related

Authorization Policy Attribute returns 403 and User.IsInRole returns false but claims are present WEB API Azure AD (Single Tenant)

Setup
I have an ASP.NET Core MVC web app configured with Azure AD. I have an ASP.NET Core Web API configured Azure AD.
I obtain the token from Azure AD in the client web app and use it when requesting resources from the Web API, this works fine.
Issue
The '[Authorize(Policy = 'policyName')]' attribute returns 403 and User.IsInRole() returns false in the WEB API controller, however when I remove the authorize policy attribute and check the user claims object, I can see the role present. Please check the image below
Claims Image
RoleClaimType Image
In my startup file I have configured token validation parameters of roleClaimType to be roles
`services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>{
// Use the groups claim for populating roles
options.TokenValidationParameters.RoleClaimType = "roles";
});`
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.
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.AddMicrosoftIdentityWebApiAuthentication(Configuration)
.EnableTokenAcquisitionToCallDownstreamApi()
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
// Use the groups claim for populating roles
options.TokenValidationParameters.RoleClaimType = "roles";
});
services.AddAuthorization(options =>
{
options.AddPolicy(Constants.AssignmentToAccountCreatorsRoleRequired, policy => policy.RequireRole(Constants.CAN_CREATE_ACCOUNT));
});
services.AddDbContext<DbContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));
//services.BuildServiceProvider().GetService<DbContext>().Database.Migrate();
services.AddAutoMapper(typeof(Startup));
services.AddControllers().AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
//TODO: Replace CORS configuration
services.AddCors(c => c.AddDefaultPolicy(policy => {
policy.WithOrigins("https://localhost:44385", "https://someweb.net/")
.AllowAnyHeader()
.AllowAnyMethod();
}));
services.AddControllers();
services.AddScoped<ConfigurationModel>();
//services.AddScoped<GraphProfileClient>();
//services.AddScoped<GraphEmailClient>();
services.AddMemoryCache();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "NAPI", Version = "v1" });
});
}
// 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.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
I noticed the options for AddAuthorization() policy in the startup.cs contains a RequireClaim method which takes in the claimType and the allowedValue(s). RequireClaim(String, IEnumerable)
services.AddAuthorization(options =>
{
options.AddPolicy("AssignmentRoleRequired", policy => policy.RequireClaim("roles", "canDoSomething"));
}); //Startup.cs
[Authorize(Policy = "AssignmentToRoleRequired")] //For Controllers
Similarly the User Object also contains a method called HasClaim(), that takes in the claimType and the allowed value.
Within a controller HasClaim(String, String)
var result = User.HasClaim("roles", "canDoSomething"); //returns true

.net core 5 app blocking due to CORS policy

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");

CORS Angular 10 ASP.Net

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");
}));

Net 2.1, Angular 7, blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested

I am getting blocked by CORS policy. I have allowed access to all in my startup.cs This is my startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddDbContext<Models.StockContext>(opt => opt.UseInMemoryDatabase("item"));
app.UseCors(builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyHeader();
});
just add this lines in your ConfigureServices part and it should work fine:
var corsBuilder = new CorsPolicyBuilder();
corsBuilder.AllowAnyHeader();
corsBuilder.WithMethods("GET", "POST");
corsBuilder.AllowAnyOrigin();
services.AddCors(options => options.AddPolicy("AllowAll",corsBuilder.Build()));
Please follow the documentation.
First, you need to enable CORS middleware inside ConfigureServices()
Second, you need to tell application to use this middleware inside Configure()
Example:
In ConfigureServices():
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
In Configure():
app.UseCors("AllowAllOrigins");

CORS in .NET Core 2.0 "No 'Access-Control-Allow-Origin' header is present on the requested resource."

I have created a web api using Core 2.0 and when doing cross domain calls w/ cors enabled, receive the following error: "No 'Access-Control-Allow-Origin' header is present on the requested resource."
Below is my config in startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddLogging();
services.AddMvc();
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAll"));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc();
app.UseCors("AllowAll");
}
According to every post/tutorial I see on stackoverflow or else where, this is the correct way to do it to allow all origins. What am I missing?
Try calling: app.UseCors("AllowAll"); before app.UseMvc();.
The documentation states the following:
To enable CORS for your entire application add the CORS middleware to your request pipeline using the UseCors extension method. Note that the CORS middleware must precede any defined endpoints in your app that you want to support cross-origin requests (ex. before any call to UseMvc).
I may be wrong, but this tutorial should help you out.
https://www.pointblankdevelopment.com.au/blog/113/aspnet-core-20-angular-24-user-registration-and-login-tutorial-example
Below is the config in startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddDbContext<DataContext>(x => x.UseInMemoryDatabase("TestDb"));
services.AddMvc();
services.AddAutoMapper();
// configure strongly typed settings objects
var appSettingsSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
// configure jwt authentication
var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
// configure DI for application services
services.AddScoped<IUserService, UserService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
// global cors policy
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
app.UseAuthentication();
app.UseMvc();
}

Resources