Defining CROS Policies
CROS needs to allow from the backend while handling CROS. Request from frontend-only defines what data need from the backend whereas the security is determined by our backend policies.
CROS policy can be configured using backend or server configs. From both way user can configure only one because configuration can both side create issue.
Ā
services.AddCors(optionsĀ =>Ā Ā
Ā Ā options.AddPolicy("Development",Ā builderĀ =>Ā Ā
Ā Ā {Ā Ā
Ā Ā Ā Ā //Ā AllowĀ multiple HTTPĀ methodsĀ Ā
Ā Ā Ā Ā builder.WithMethods("GET",Ā "POST",Ā "PATCH",Ā "DELETE",Ā "OPTIONS")Ā Ā
Ā Ā Ā Ā Ā Ā .WithHeaders(Ā Ā
Ā Ā Ā Ā Ā Ā Ā Ā HeaderNames.Accept,Ā Ā
Ā Ā Ā Ā Ā Ā Ā Ā HeaderNames.ContentType,Ā Ā
Ā Ā Ā Ā Ā Ā Ā Ā HeaderNames.Authorization)Ā Ā
Ā Ā Ā Ā Ā Ā .AllowCredentials()Ā Ā
Ā Ā Ā Ā Ā Ā .SetIsOriginAllowed(originĀ =>Ā Ā
Ā Ā Ā Ā Ā Ā {Ā Ā
Ā Ā Ā Ā Ā Ā Ā Ā ifĀ (string.IsNullOrWhiteSpace(origin))Ā returnĀ false;Ā Ā
Ā Ā Ā Ā Ā Ā Ā Ā ifĀ (origin.ToLower().StartsWith("http://localhost"))Ā returnĀ true;Ā Ā
Ā Ā Ā Ā Ā Ā Ā returnĀ false;Ā Ā
Ā Ā Ā Ā Ā Ā });Ā Ā
Ā Ā })Ā Ā
);Ā Ā
The policy builder allows us to add different HTTP request methods, Accept, Content type, and Authorization Header. Allow credentials are used to pass cookies successfully. For allowing credentials we need to allow origins. Call CORS policies using IApplicationBuilder.
Ā
//Allows CROS policies we defined
App.UseCors(āDevelopmentā);]