401 Unauthorized status code for cross-domain OPTIONS request - angularjs

I use cross-domain requests for Angularjs + MVC WebAPI, in the case browser sends two requests first of them with OPTIONS type but i get 401 status code:
http://grab.by/vrsA
I added Access-Control-* attributes to WebApi web.config file:
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By"/>
<remove name="X-AspNet-Version"/>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="content-type, accept, authorization, origin, referer, user-agent, x-token"/>
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
</customHeaders>
</httpProtocol>
so, can somebody explain my why?

The preflight (OPTIONS) request is sent without any security headers. You'll need to make sure that your webserver allows anonymous OPTIONS requests

Related

AngularJS + Asp.net WebApi - Cannot get authentication to work due to CORS

I have an AngularJS app which talks to an ASP.Net WebApi backend.
Both the UI and the API are hosted on the same domain/server, but on different ports:
UI: https://www.example.com
API: https://www.example.com:8888
The UI is successfully communicating with the API for all required HTTP Methods (GET, POST, etc.), but I cannot get authentication to work.
When the call to "/login" is made, I get the following response from the API:
Access to XMLHttpRequest at 'https://www.example.com:8888/api/login' from origin 'https://www.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Excerpt of Web.Config from ASP.Net WebApi
<configuration>
<system.webServer>
...
<httpProtocol>
...
<customHeaders>
<clear />
<!-- CORS Configuration -->
<add name="Access-Control-Allow-Origin" value="https://www.example.com" />
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="*" />
<add name="Access-Control-Allow-Credentials" value="true" />
<!-- /CORS Configuration -->
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
There is no other CORS-related configuration within the API app.
Call to authenticate from AngularJS front-end
attemptLogin (userId, password) {
var data = {
UserId: userId,
Password: password
};
return this.$http.post("https://www.example.com:8888/login", data, { withCredentials: true });
}
Interestingly...
... if I set the "Access-Control-Allow-Origin" header to wildcard "*", I get a different message, which would indicate that the API is correctly identifying the API call as relating to authentication.
Access to XMLHttpRequest at 'https://www.example.com:8888/api/login' from origin 'https://www.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
Can anyone shed any light on what I'm doing wrong?
You might need to include the port you're using on UI. Like this:
<add name="Access-Control-Allow-Origin" value="https://www.example.com:4200" />

Dotnetnuke Braintree - XMLHttpRequest cannot load transparent redirect

I'm trying to develop a braintree payment gateway (transparent redirect) on my dotnetnuke website and while I was developing on development site with http development everything worked. When i put my code in the production website with https, i have this error on my chrome console and not works!
After some search i put this on my web.config:
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
And my payment still works and a receive the transparent url:
<--urlbase-->?http_status=200&id=xxx&kind=create_transaction&hash=xxx
But when execute:
Result<Transaction> chargeResult = this.BraintreeGateway().TransparentRedirect.ConfirmTransaction(this.Request.Url.Query);
Nothing happens! I don't have errors in the event viewer!

OWIN: webapi call returning 401 unauthoried Error in Azure

I have created two applications one for front end(created using AngularJs and Asp.Net MVC) and for backend I used web Api application.
I am trying to secure my application with forms authentication in front End and implemented basic forms authentication in back End.
When I tested locally in IIS it works fine.But when I hosted my application in Azure, API call with authentication attribute returns with 401 unauthorized error.
response Header:
Access-Control-Allow-Origin:*
Cache-Control:no-cache
Content-Length:0
Date:Wed, 05 Oct 2016 11:08:30 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/8.0
Set-Cookie:ARRAffinity=925cd503f9e5771e9ad651c59baa4a1f678d93cac8b9da4dc9bcb64892ac8710;Path=/;Domain=FrontEnd.azurewebsites.net
WWW-Authenticate:Basic realm="Backend.azurewebsites.net"
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
Request Header;
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Host:backend.azurewebsites.net
Origin:http://FrontEnd.azurewebsites.net
Pragma:no-cache
Referer:http://FrontEnd.azurewebsites.net/
Token:null
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36
But in local along with request header
Authorization: Basic dmlzaG53guFua2FyLnNha3Roadh4bEBnbWFpbC5jb206MTIzMTIz
Cookie: __RequestVerificationToken_L3Nfg4dwc3Bh0=YGwlXkckjhg6xTESkI-lN9sNtDVsfefshsrvGWPKekmv_GLZ0Rq8eA5P8Z7sdf4trwbPX4WymcGJJrLamQLMe2Vf2D2fVUg4qJptOvcsCWg1; ASP.NET_SessionId=gk4s1rlsfg5gfeafo3455dkr; .ASPXAUTH=C8113FD23FC4902dsfrsdf5FB3399BA121703F41F9A57AEA50667F2AD4FC02F3D3955215A91F6A3A2EA4287202522380435A93D8BE78D45E6D24FB7E05F64653AE06E0026DEB2911343591563F70EE8EE76338F07CBABE6EA4B95359F3C31sdf9C999sdf2864849gfdB916A06gfds29E3C8D01D2371807E98335000D4D14B391CCE3zxcd49DB77696F4BB77E4434
is passed
Authorization and Cookie parameter is not get added in request from azure frontEND app with forms authentication.
I Looked into authentication/authorization configuration of my backend app in azure it sets off.can any body know what is the issue or what I need to configure in azure portal.Thanks in advance.
This issue is due to cors
you can solve this by adding in your request,
$http({
....
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
withCredentials: true,
})
WEB.Config of web API
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="**FrontEnd URL**" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Cache-Control" />
<add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
you also refer this URl as well:
https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
This is probably because they are no longer hosted on the same machine (depending on your Azure setup). I've had a similar problem with machineKey myself.
Follow the instructions in the following URL to match up the settings between the applications and you should be fine:
https://msdn.microsoft.com/en-us/library/eb0zx8fc.aspx
EDIT: With Access-Control-Allow-Origin:* in the response header it is probably not a normal CORS problem, although machineKey and CORS problems often come together. If the machineKey fix does not work, check how you are handling CORS pre-flight checks. See my answer here.

401 Unauthorized error when accessing webapi from angular

I need to capture a user's domain\username when they access my webapi app. On my dev machine I have my webapi at localhost:10570 and my angularjs website which makes calls to the webservice at localhost:34575.
If I make a call directly to my webapi app everything works fine. I can see the users domain and username and the service returns the requested data as JSON. But if I access my angularjs site and angular makes the call to webapi then I get 401 unauthorized for every call against the service.
In my WebApi app's web.config I have:
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<authentication mode="Windows" />
</system.web>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:34575" />
<add name="Access-Control-Allow-Methods" value="POST, PUT, DELETE, GET, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="content-Type, accept, origin, X-Requested-With, Authorization, name" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</system.webServer>
I have this in IIS Express for Visual Studio 2015's applicationhost.config file:
<location path="MyNamespace.WebAPI">
<system.webServer>
<security>
<authentication>
<windowsAuthentication enabled="true" />
<anonymousAuthentication enabled="false" />
</authentication>
</security>
</system.webServer>
</location>
My angularjs site is part of the same solution at "MyNamespace.Client".
Why does accessing the web service directly work fine, but accessing it via the angular app fail?
I didn't realize you have to tell Angular to send your credentials to the server. I just had to change my API calls from:
$http.get(url);
to
$http.get(url, { withCredentials: true });

Response to Preflight responded with 405 Error code : Angular JS

I am using an API call in cross domain where In chrome I am getting this response . I have all the headers included in my REST API in other domain .
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="X-Content-Type-Options" value="nosniff"/>
<add name="X-XSS-Protection" value="1;"/>
<remove name="X-Powered-By"/>
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept"/>
<add name="Access-Control-Allow-Methods" value="POST,GET"/>
And this is my API Call from angular .
$scope.XYZ=customURLWithoutArray.save({
controller:"XYZController",
actionName:"ABCACTIONNAME",
UserId: "VC"
},
function($success){
return $success;
},function($error){
return $error;
});
It is able to hit the controller but data is null.
As you might already know, a preflight request sends a HTTP OPTIONS request.
In your configuration (I assume its some IIS server?) you have this:
<add name="Access-Control-Allow-Methods" value="POST,GET"/>
Which means you're not allowing OPTIONS.
So try modifying it to this:
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS/>
More information on configuring IIS for CORS:
https://stackoverflow.com/a/31084417/6139050

Resources