Thursday, April 13, 2017

Asp.net Core MVC CORS preflight issue REST api

Browser -> CORS -> IIS -> Kestrel Asp.net Core MVC REST apis

Project:
Silverlight migration project into HTML5/AngularJS/Asp.net Core MVC.

Problem:
CORS preflight (http options) request was throwing 403 forbidden error.

Story & Solution:

I did hosted Asp.net core REST apis on IIS, initially UI\AngularJS developers were consuming basic GET api's everything was going smooth.
Next, when they tried to consume my http POST apis, panic button pressed its not working.

Unlike WFC, xml web services, web apis, Asp.Net Core MVC has brand new web server called 'Kestrel' which is faster and modern compared to IIS. But Kestrel is not matured enough to put behind internet so we have to do reverse proxy using IIS, basically IIS forwards http calls to kestrel and vice versa. Story doesn't end their to make complicated, when angularjs or client makes calls from modern browsers, it will make a preflight call to web server to make sure request service is available and client has access, this is for security purpose according W3C CORS standard. So browser make a preflight http OPTIONS request, but most web server doesn't enable or accept http OPTIONS, PUT, Delete requests, admin disables it by default Then developer have to scratch his head and trace where its going wrong.

Solutions:

So, when you stuck, pls go through the following areas, which might help you to solve the issue.

a) Enable http log at IIS level, go through the logs.

b) Enable logging at asp.net core mvc api.

c) Use Fiddler or REST api client like postman(beware unlike browser postman doesn't make preflight request, it works here but from browser it fails)

d) In web config allow required verbs

e) Verify url scan config.

f) Verify and make sure all the required configs are enabled system32\inetserv\config applicationhost root config file for IIS.


Pls make sure changes you do must be compliance towards company cyber security policies.

PS: above tips works well other web servers; apache, nginx ...