has been blocked by CORS policy --why am I getting this error for post request in asp.net core? - asp.net-core

for GET request, I got the same error and I fixed that but now for POST request again getting this error. For the GET request I fixed that by writing this in a startup.cs file. What can I do?
public void ConfigureServices(IServiceCollection services) {
services.AddCors(options => {
options.AddPolicy(name: MyAllowSpecificOrigins,
builder => {
builder.WithOrigins("https://localhost:fhfhhfh",
"https://localhost:fhfhf");
});
});
services.AddControllers();
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, GameUserContext db) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
db.Database.EnsureCreated();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseCors(MyAllowSpecificOrigins);
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
endpoints.MapRazorPages();
});
}

Allow POST method by extending your builder like this:
builder.WithOrigins("https://localhost:fhfhhfh", "https://localhost:fhfhf")
.WithMethods("POST", "GET");
WithMethods
Or you can allow any method:
builder.WithOrigins("https://localhost:fhfhhfh", "https://localhost:fhfhf")
.AllowAnyMethod();
AllowAnyMethod

Change app.UseCors() to app.UseCors(MyAllowSpecificOrigins);
if it is still not working
try to change your builder to builder => {
builder.WithOrigins("https://localhost:fhfhhfh",
"https://localhost:fhfhf")
.AllowAnyHeader()
.AllowAnyMethod();
});

Related

Enabling CORS in ASP.NET Core 6

I have an ASP.NET Core 6 Web API that has a react front end.
I would like to use named policies to enable cors so I have in my startup
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("MyPolicy",
builder => builder.WithOrigins("http://localhost:3000/"));
});
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
// Shows UseCors with named policy.
app.UseCors("MyPolicy");
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
Now I can call it in the controller like this:
[EnableCors("MyPolicy")]
public class ProductsController : ControllerBase
This worked in .NET Core 3.1 but not in .NET 6.
What is the right way of doing this in an ASP.NET Core 6 Web API?
Changing the program CS to acomodate CORS policy still doesnt work
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
using var scope = host.Services.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<StoreContext>();
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
try
{
context.Database.Migrate();
DbInitializer.Initialize(context);
}
catch (Exception ex)
{
logger.LogError(ex, "Problem migrating data");
}
var builder = WebApplication.CreateBuilder(args);
var MyAllowSpecificOrigins = "AnotherPolicy";
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<StoreContext>(options =>
{
options.UseSqlite(connectionString);
});
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
app.MapControllers();
try
{
app.Run();
}
catch (Exception)
{
throw;
}
//host.Run();
}
This gives me the same error
Access to fetch at 'http://localhost:5000/api/Products' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
in program.cs file:
app.UseCors(
options => options.WithOrigins("*").AllowAnyMethod().AllowAnyHeader()
);
As noted in the documentation:
The specified URL must not contain a trailing slash (/). If the URL terminates with /, the comparison returns false and no header is returned.

How to get raw request header in token validation stage of IdentityServer4 (asp.net core)?

I need to read the IP address from request header in ResourcePasswordValidator when people login. But I could not find it in ResourceOwnerPasswordValidationContext. The document I followed: https://identityserver4.readthedocs.io/en/latest/topics/resource_owner.html
PS: LocalApiAuthentication is used, and I'm new to IdentityServer4 framework. Thanks.
Codes in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiScopes(ApiConfig.GetApis())
.AddInMemoryClients(ApiConfig.GetClients())
.AddInMemoryIdentityResources(ApiConfig.GetIdentityResources())
.AddResourceOwnerValidator<ResourcePasswordValidator>()
.AddProfileService<ProfileService>();
services.AddLocalApiAuthentication();
services.AddAuthorization(options =>
{
options.AddPolicy(IdentityServerConstants.LocalApi.PolicyName, policy =>
{
policy.AddAuthenticationSchemes(IdentityServerConstants.LocalApi.AuthenticationScheme);
policy.RequireAuthenticatedUser();
});
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseIdentityServer();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Inside OWIN Startup.cs, add the password validator middleware to your Identity configuration:
services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
options.SignIn.RequireConfirmedEmail = false;
options.SignIn.RequireConfirmedPhoneNumber = false;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddUserStore<ApplicationUserStore>()
.AddRoleStore<ApplicationRoleStore>()
.AddUserManager<ApplicationUserManager>()
.AddRoleManager<ApplicationRoleManager>()
.AddPasswordValidator<IResourceOwnerPasswordValidator>() //right here
.AddDefaultTokenProviders();

Blazor Server Side app won't redirect to login page after IIS WebSite is restarted

After I restart IIS Website, I get following error, instead of being redirected to login page:
blazor.server.js:1 POST https://localhost/_blazor/negotiate?negotiateVersion=1 net::ERR_ABORTED 401
when visiting https://localhost/someblazorroute.
I need to manually go to https://localhost/ and hard reload the page (in chrome Ctrl+Shift+R) in order to be redirected to login
I have following startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<IISServerOptions>(options => options.AutomaticAuthentication = false);
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Auth/Login";
options.LogoutPath = "/Auth/Logout";
})
.AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler >("Basic", null);
services.AddAuthorization(options =>
{
options.AddPolicy("AllowBasicAuthPolicy", policy =>
{
policy.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme);
policy.AddAuthenticationSchemes("Basic");
policy.RequireAuthenticatedUser();
});
});
}
// 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();
}
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.MapRazorPages().RequireAuthorization();
endpoints.MapBlazorHub().RequireAuthorization();
endpoints.MapFallbackToPage("/_Host");
});
}
I was facing the exact same issue and the solution to this was rather trivial.
you just need to ensure that you call for setting up Authentication, Authorization and then set default route in the right order in startup.cs as shown in the code below:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
.
.
.
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
//this MUST come after the lines before.
app.UseMvcWithDefaultRoute();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}

ASP.NET Core 3.1 - routing Issue

Since upgrading to 3.1, I seemed to have lost my routing. My endpoints are now just returning a 404 and I have ran out of ideas of what the issue could be. Can anyone see if I'm doing something stupid in my below setup code? All that really changed in my setup code was that I stopped using
app.UseMvc
And now use the endpoint instead
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Code below
[ApiController]
[Authorize]
[Route("api/guild")]
public class GuildController : Controller
{
[HttpPost("create")]
public async Task<IActionResult> Create([FromBody]CreateGuildRequest request)
{
return Ok();
}
}
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)
{
var domain = Configuration["Auth0:Domain"];
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = domain;
options.Audience = Configuration["Auth0:Audience"];
});
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true)
.AllowCredentials()
.Build());
});
services.AddControllers();
services.AddSpaStaticFiles(configuration => { configuration.RootPath = "clientapp/dist"; });
}
// 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();
}
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.UseSpaStaticFiles();
app.UseRouting();
app.UseSpa(spa =>
{
spa.Options.SourcePath = "clientApp";
if (env.IsDevelopment())
{
spa.UseVueCli(npmScript: "serve", port: 8080);
}
});
app.UseCors("CorsPolicy");
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Middleware order matters. Place your UseSpa() after UseEndpoints()
// this should be the last two middlewares, in this order
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "clientApp";
if (env.IsDevelopment())
{
spa.UseVueCli(npmScript: "serve", port: 8080);
}
});

User registration event ASP.NET Core 3

I've created an ASP.NET Core 3 website with all the latest updates (Visual Studio 2019). I would like to perform certain actions when a user registers but I cannot find out how to do that. I suspect that I have to hook up to an event in my start up class, but all my googling has left me in loops. Please assist. My current startup class looks like this (it's mostly the generated code)
public void ConfigureServices(IServiceCollection services)
{
services.TryAddTransient<ITokenService, CustomTokenService>();
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>().AddEntityFrameworkStores<ApplicationDbContext>();
services.AddIdentityServer().AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
services.AddAuthentication().AddIdentityServerJwt();
services.AddControllersWithViews();
services.AddRazorPages();
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseAuthentication();
app.UseIdentityServer();
app.UseAuthorization();
app.UseHttpsRedirection();
app.UseStaticFiles();
if (!env.IsDevelopment())
{
app.UseSpaStaticFiles();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(name: "default", pattern: "{controller}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}