This series is divided into three parts:
- Set up AWS Cognito and backend Web API user functions - previous post
- Configure CORS in Web API backend - this post
- Authentication between frontend and Web API backend - next post
Since our frontend Angular app may be in different domain or at least port number in development (using localhost), we need to allow Cross-Origin Resource Sharing (CORS) in the backend Web API. There are two approaches for this, whether to allow only some methods by using a named policy or apply to all methods.
In ConfigureServices method inside Startup.cs file, to allow CORS for selected methods only, we put:
services.AddCors(options => { options.AddPolicy("EnableCORS", builder => builder.WithOrigins("http://localhost:4200", "https://localhost:4200") // frontend domain(s) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials() //.WithMethods("OPTIONS", "GET") ); });
Then in Configure method, add:
. . . app.UseCors("EnableCORS"); . . .Important! Make sure to put app.UseCors() code in the right order as specify in the ASP.NET Core documentation
Then on the controller methods, we add EnableCors attribute, for example:
[EnableCors("EnableCORS")] [HttpGet] public IEnumerable<WeatherForecast> Get() { . . . }
If we want to enable CORS for all methods, we use AddDefaultPolicy() instead AddPolicy():
services.AddCors(options => { options.AddDefaultPolicy(builder => builder.WithOrigins("http://localhost:4200", "https://localhost:4200") // frontend domain(s) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials() //.WithMethods("OPTIONS", "GET") ); });Then in Configure method, just put:
app.UseCors();
On the next post, we will configure the Authentication part in the project.
No comments:
Post a Comment