Having problem with Pre-flight CORS request with your Angular 2 App and Web API 2?

There are many solutions posted regarding Pre-Flight CORS error at the client application when accessing your ASP.Net Web API 2 server application.  The problem is caused by CORS security implementation at the browser level, the solution is very simple though, just enable the CORS response at the server application, in our case, we should enable CORS in our ASP.Net Web API 2 application.  But it is easier said than done, because there are two issues to consider:

  1. Token authentication via /Token – asking for authorization by authentication.
  2. Api Bearer authorization access via /Api – asking for resources using authorized bearer token.

To solve the first issue, you just need to modify the Web.config file of your ASP.Net Web API 2 server application by adding the following entries inside the <configuration> …</configuration> tag.

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

To solve the second issue just insert the following code in the Register method at the App_Start\WebApiConfig.cs file.

public static void Register(HttpConfiguration config)
{
     var cors = new EnableCorsAttribute("*", "*", "*");
     config.EnableCors(cors);

     config.SuppressDefaultHostAuthentication();
     config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

     config.MapHttpAttributeRoutes();
     config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
}

But you cannot do both!  what I mean is, if you fix the first issue, the second issue will not work and vice versa.  It’s a f$%k’n nightmare!  And to add to the injury, fixing the second issue requires you to add new references to your project that may conflict to the current version.

The real solution to the problem is to disregard both the solutions posted above and just use the OWIN.CORS package (Install-Package Microsoft.Owin.Cors), then modify the the ConfigureAuth method in the App_Start\Startup.Auth.cs file with the following code:

public void ConfigureAuth(IAppBuilder app)
{
     app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
     app.UseCookieAuthentication(new CookieAuthenticationOptions());
     app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
     app.UseOAuthBearerTokens(OAuthOptions);
{

The above solution enables CORS at startup, thus, this will include both the /Token and /Api routes to the CORS Pre-flight.

Here are the codes and screen-shots of the UI at the client side (I’m using Angular 2 Typescript by the way), just google for the jQuery equivalent.  My goal in life is not to write anymore Javascript code! :p

Authorization Token:

let url = "http://localhost:9000/Token";
let body = "username=" + username + "&password=" + password + "&grant_type=password";
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });        

this._http.post(url, body, options).subscribe(
    response => {
        localStorage.setItem('access_token', response.json().access_token);
        localStorage.setItem('expires_in', response.json().expires_in);
        localStorage.setItem('token_type', response.json().token_type);
        localStorage.setItem('userName', response.json().userName);

        window.location.replace('/dashboard');
    },
    error => {
        console.log(error.json().error_description);
    }
);

u1

Resources API:

let url = "http://localhost:9000/Api/TableGroups";
let headers = new Headers({ 'Authorization': 'Bearer ' + localStorage.getItem('access_token') });
let options = new RequestOptions({ headers: headers }); 

this.http.get(url, options)
    .subscribe(
        response => {
            for (var key in response.json()) {
                if (response.json().hasOwnProperty(key)) {
                    data.push({
                        id: response.json()[key].Id,
                        tableCode: response.json()[key].TableCode,
                        tableGroupId: response.json()[key].TableGroupId,
                        tableGroup: response.json()[key].TableGroup,
                        topLocation: response.json()[key].TopLocation,
                        leftLocation: response.json()[key].LeftLocation
                    });
                }
            }
        },
        error => {

        }
    );

u2

Thats it!  If you are using Innosoft POS, the screen shots looks familiar!  Yes! we are modifying the POS using pure HTML 5 and sad to say I will be using Google technology!

And if you find this blog helpful, you can make the donation by clicking the Paypal button below.


					
Advertisements
About

Software developer living in the Philippines.

Posted in ASP.NET
One comment on “Having problem with Pre-flight CORS request with your Angular 2 App and Web API 2?
  1. Mike says:

    Thanks, this really helped me out. Been searching like forever, and this is a simple solution!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Author

Harold Glenn P. Minerva
Software Developer / Tech Enthusiast
Living in the Philippines

View Harold Glenn Minerva's profile on LinkedIn

Instagram

Software Engineer - Seasonal and Range Trading Software. Magenta Trader is a powerful stock market visualization software that increases your probability of trading success.

Software Architect and Founder - Easyfis.com is a multi-tenant cloud-based Software-as-a-Service (SaaS) business app that caters to micro, small and medium trading businesses.

CTO and Co-Founder - We give your company the leverage by providing innovative software solutions products such as Point-of-Sales (POS), Financial Information System (FMIS), Payroll and DTR (HRIS), and many more.

%d bloggers like this: