401 error when using a web service in sapui5

2.4k views Asked by At

I am implementing a web service into my sapui5 table by

var oModel = new sap.ui.model.odata.ODataModel("http://mywebservice.com/security.svc", false);
sap.ui.getCore().setModel(oModel);

When I launch my code in a web browser and inspect element, I am getting the following errors:

Failed to load resource: the server responded with a status of 401 (Unauthorized)

XMLHttpRequest cannot load http://mywebservice.com/security.svc/$metadata. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:53457' is therefore not allowed access. The response had HTTP status code 401.

I also tested it in Fiddler and I get:

HTTP/1.1 401 Unauthorized
Cache-Control: private
Server: Microsoft-IIS/8.0
Set-Cookie: ASP.NET; path=/; HttpOnly
X-AspNet-Version: 4.0.30319
WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM
X-Powered-By: ASP.NET
Date: Tue, 09 Jun 2015 19:33:51 GMT
Content-Length: 0
Proxy-Support: Session-Based-Authentication

Any help on how to fix the 401 error would be greatly appreciated.

2

There are 2 answers

0
Sunil B N On

Creating a new ODataModel, it tries to fetch the metadata for the service you have called. It's basically XMLHttpRequest to a different domain(http://mywebservice.com) than you page(localhost) is on.So the browser is blocking it as it usually allows a request in the same origin for security reasons. Read about same-origin policy

Solution: You need to do something different when you want to do a cross-domain request. the origin (where the page with JavaScript is at) and the target: http://mywebservice.com (where the JavaScript is trying to reach) domains must be the exact same. A tutorial about how to achieve that is Using CORS.

In .NET server,you can configure this in web.config as below

 <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="your_clientside_websiteurl" />
     </customHeaders>
   </httpProtocol>
 <system.webServer>
0
anjaly On

Just clone the shortcut for chrome on your desktop, and then in the shortcut properties add the parameter --disable-web-security at the end of chrome executable path e.g "C:\Program Files\Google\Chrome\Application\chrome.exe" --disable-web-security

NB:add that parameter --disable-web-security in Target location after one space