Reputation: 700
.Net Core 2.1 rest api with the client (react) app, when I try to fetch from rest api (http://localhost:44334) to the client (http://localhost:3000), I get this exception:
Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information: Policy execution failed. Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information: Request header 'access-control-allow-origin' not allowed in CORS policy. Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 3.9493ms 204
But on the react client on browser i get this:
Access to fetch at 'https://localhost:44334/Account' from origin 'http://localhost:3000' 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.
This is my c# class when i register cors, i remember to register instance behind .AddMvc method
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator"));
});
services.AddCors();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddOptions();
services.AddMemoryCache();
var jwt_settings = Configuration.GetSettings<JwtSettings>();
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(cfg =>
{
cfg.TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt_settings.Key)),
ValidIssuer = jwt_settings.Issuer,
ValidateIssuer = false,
ValidateAudience = false,
ValidateIssuerSigningKey = true,
ValidateLifetime = true
};
});
var builder = new ContainerBuilder();
//register commandModules
builder.Populate(services);
builder.RegisterModule(new ContainerModules(Configuration));
ApplicationContainer = builder.Build();
return new AutofacServiceProvider(ApplicationContainer);
}
And register on Configure method:
app.UseCors(
options => options.WithOrigins("http://localhost:3000").AllowAnyMethod()
);
app.UseMvc();
And this i paste the react code where i fetch api:
export function login(password, email) {
fetch("https://localhost:44334/Account", {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json",
// "Content-Type": "application/x-www-form-urlencoded",
'Accept': 'application/json',
"Access-Control-Allow-Origin": "*"
},
body: {email, password}
}).then(res => res.json())
.then(response => console.log('Success:', response))
.catch(error => console.error('Error:', error));
}
And the controller method on this i dont use EnableCors:
[HttpPost]
public async Task<IActionResult> Login([FromBody] LoginAsync login)
{
login.TokenId = Guid.NewGuid();
await _commandDispatcher.DispatchAsync(login);
var jwt = _memoryCache.Get<JsonWebToken>(login.TokenId);
return Json(jwt);
}
Upvotes: 5
Views: 18022
Reputation: 2670
To add just any request:
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
);
});
and use:
app.UseCors("CorsPolicy");
Upvotes: 0
Reputation: 640
Add below code Within Configure services method
services.AddCors(options =>
{
// this defines a CORS policy called "default"
options.AddPolicy("default", policy =>
{
policy.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
Within configure method
app.UseCors("default");
Upvotes: 10