Tristan Tristan - 2 months ago 36
reST (reStructuredText) Question

Not able to request WSO2 API (with CORS activated) via AngularJS

When my client AngularJS app tried to reach some REST API exposed via WSO2 API Manager (v2.0.0), I get this response (IP, port replaced with "am_host" and "am_port") :

Refused to set unsafe header "Origin"
XMLHttpRequest cannot load http://am_host:am_port/ReferentielInfoConso/offres-tarifaires/identifiants. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access.


I can confirm "Access-Control-Allow-Origin" header is not present in the response to the "OPTIONS" request when I check the headers in Chrome developper tool.

header_chrome

When I request the same URL with same HTTP method (GET /ReferentielInfoConso/offres-tarifaires/identifiants HTTP/1.1) in Chrome Advanced REST Client, I can see the expected header "Access-Control-Allow-Origin" and I can get access to the resource :

capture_rest_client

So what should I do to make it work in my AngularJS App (without creating a Node.js backend, I need to keep it very light) ? Why enabling CORS in WSO2 is not enough ?

EDIT : If my AngularJS app requests the API directly to the Tomcat 7 endpoint (CORS enabled by default) without going through WSO2 AM, it works perfectly.

EDIT 2 : When my AngularJS App tries to reach the WSO2 API without sending the authorization token, I get a 401 response including the expected "Access-Control-Allow-Origin" header. As soon as I add the token, it looks like it follows a different route through WSO2 AM and I don't get the "Access-Control-Allow-Origin" header.

EDIT 3 : if I had an "Autorization" header and try to reach my Tomcat 7 backend directly, I get a "cross-origin" problem too but I guess it's because "Authorization" header is not in the list of headers allowed in Tomcat conf. It is in the list of headers allowed by WSO2 AM though (I've added both "authorization" and "Authorization" to be sure it will work).

Answer

For my particular situation, where I want client apps to request a token and call APIs in AJAX, I've chosen the simplest solution : configuring an Apache web server on the same machine as WSO2 with these simple conf lines below.

    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Methods "GET,PUT,POST,DELETE,PATCH,OPTIONS"
    Header set Access-Control-Allow-Headers "authorization,Access-Control-Allow-Origin,Content-Type,SOAPAction,Authorization"

    ProxyPass "/" "http://10.22.106.101:8280/"
    ProxyPassReverse "/" "http://10.22.106.101:8280/"