I'm doing some code here i need to send a request from javascript client with a username and a password to a web api. In this request i need to receive a token.
This is what i have now:
var loginData = {
grant_type: 'password',
//Username and password are fill by the user in the text fields
username: username,
password: password
};
$.ajax({
type: 'POST',
crossDomain: true, //I'm having some problems with: Access-Control-Allow-Origin
crossOrigin:true,
contentType: "application/json",
url: 'https://localhost:44380/Token',
data: loginData
}).done(function (data) {
self.user(data.userName);
sessionStorage.setItem("Token", data.access_token);
}).fail("Error");
When i execute the client i receive erros related to Access-Control-Allow-Origin
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 400.
And
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
Any ideas? I'm a rookie in web ...
I'm not sure if i'm doing the ajax request correctly...
Add web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://[your service domain]" />
<add name="Access-Control-Allow-Methods" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization"/>
<add name="Access-Control-Allow-Credentials" value="true"/>
</customHeaders>
</httpProtocol>
</system.webServer>
You need to enabled cors in your project
here's a link to help you
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Related
I'm testing an Ajax request to an external address using Visual Studio and IIS Express on my Localhost. (I've tested this request using Fiddler and it works ok!)
When i run it, I see the following in the browser (Chrome) console:
Access to XMLHttpRequest at 'https://api.example.com/' from origin 'https://localhost:44306' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I've trawled SO and I've tried adding the following:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,HEAD,OPTIONS" />
<add name="Access-Control-Expose-Headers" value="*" />
<add name="Access-Control-Request-Headers" value="*" />
<add name="Access-Control-Request-Method" value="GET,PUT,POST,DELETE,HEAD,OPTIONS" />
<add name="X-Frame-Options" value="DENY" />
</customHeaders>
</httpProtocol>
</system.webServer>
To my project's web.config and C:\Users\xxx\Documents\IISExpress\config\applicationhost.config. I've also tried adding headers in my Global.asax such as:
void Application_PreSendRequestHeaders
And I've tried setting them as part of the Ajax request like so:
var newDataRequest = $.ajax({
type: "post",
url: 'https://api.example.com/',
crossDomain : true,
crossOrigin: true,
headers: {
"Accept": "application/json",
"Content-Type":"application/json",
"Access-Control-Allow-Origin":"https://localhost:44306/",
"Access-Control-Expose-Headers":"*",
"Access-Control-Request-Headers":"access-control-allow-credentials,access-control-allow-headers,access-control-allow-methods,access-control-allow-origin,access-control-expose-headers,access-control-max-age,content-type,key,x-frame-options",
"Access-Control-Allow-Methods" : "GET,PUT,POST,DELETE,HEAD,OPTIONS",
"Access-Control-Allow-Headers" : "Content-Type,Authorization,Accept",
"Access-Control-Max-Age" : 1728000,
"Access-Control-Allow-Credentials" : true,
"X-Frame-Options":"DENY"
},
data: {},
timeout: 60000
}).done(function (data) {
}).fail(function (jqXHR, textStatus) {
}).always(function (jqXHR, textStatus) {
stopSpinner();
});
Here are a few references to the things I have tried above:
Web.config customHeaders not returned in a response
Response to preflight request doesn't pass access control check (Angular2)
CORS problems in WebAPI hosted in IIS
Any other suggestions please? I'm running out of ideas!
Thanks!
I think this was an issue when trying to call an external API from client-side code (as opposed to server-side code).
To get around this in MVC, i pointed my ajax request to a LOCAL action like so:
url: '#Url.Action("Action", "Controller")'
and then in the action method (decorated with the [HttpPost] attribute), I used HttpWebRequest to successfully make a request to the external API.
I have a Outlook Web Addin. When tested in local(Debug environment) it works properly but when Web API is released to production and Outlook Addin is not yet released to production (Outlook store), I am getting CORS related issue and the error code which is returned while making the request is 404 and the error message returned is Response to preflight does not have HTTP ok status.
I had similar issue in the Web API local (Not released to production), but I was able to fix it by adding the below piece of code
In Web Config file (Server side)
<location path="api/v1/plugin">
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type, Accept, Token, Key" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, OPTIONS" />
<add name="Access-Control-Max-Age" value="3600" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
</system.webServer>
In Web API controller changes for HTTP Options
[HttpOptions]
[Route("login")]
public void EnableCors()
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.OK;
}
}
In the client side (Outlook plugin), I am using Ajax to make a call to Web API.
$.ajax({
type: "POST",
url: call,
async: false,
headers: {
'Token': token, 'Key': keyVal
},
contentType: "application/javascript",
beforeSend: function (xhr) {
xhr.withCredentials = true;
},
crossDomain: true,
success: function (data, status, jqXHR) {
createRoamingSetting('apiData',JSON.stringify(data));
},
error: function (jqXHR, status, err) {
triggerAlert("error", err.message);
}
});
When both the above code was included it was working fine in the Debug build. I was able to make request to the Web API(Not released - localhost). But when Web API released to Production, request to Web API returns 404 Error.
And below is the screen shot of the error which I get in the production build.
Any help would be appreciated :)
Maybe you should add <remove name="OPTIONSVerbHandler" /> in web.config within system.webServer > handlers. If this is there then check for HTTP Verbs in request filetering in your IIS, you need to remove the OPTIONS. This worked for me.
I need to consume data from a SharePoint 2010 through the REST site.
I am calling through a ajax + Jquery request.
My host is localhost and I'm trying to call a host of other domain.
I'm trying to call a sharepoint list through a typescript project that is on my local machine
I set the Cross-origin in my HEADER:
$.ajax({
type: "GET",
contentType: "application/json;charset=ISO-8859-1",
url: path,
dataType: "json",
cache: false,
headers: { 'Access-Control-Allow-Origin': '*' },
crossDomain: true,
async: false,
success: function (response) {
if (response.d.__next) {
recursive(response.d.__next);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
console.log(errorThrown);
console.log(textStatus);
console.log(XMLHttpRequest);
}
});
I set the Cross-origin in Source server WebConfig:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:50515" />
<add name="X-MS-InvokeApp" value="1; RequireReadOnly" />
<add name="Access-Control-Allow-Headers" value="Content-Type, Accept, X-Requested-With, X-File-Name"/>
<add name="Access-Control-Allow-Methods" value="GET, POST"/>
</customHeaders>
</httpProtocol>
But is taking place this error here:
XMLHttpRequest cannot load http:MyLocalHost/SiteOrigin/_vti_bin/listdata.svc/person?_=1457982013329. Response for preflight has invalid HTTP status code 401send # jquery.min.js:4
controller.js:50 DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http:MyLocalHost/SiteOrigin/_vti_bin/listdata.svc/person?_=1457982013329.'.(…)
controller.js:51 error
Already, thanks to everyone who can help me
This post is a year old so maybe the original poster gave up. Anyway You can use Nginx with a reverse proxy, eg:
location /sharepoint/ { proxy_pass http://sharepoint/;}
And you can call your request this time to 'http://localhost/sharepoint/'. Last thing, it's very important to change in SharePoint Central Administration (Central Admin, Security and then Specify Authentication Providers) IIS7 Basic Auth enable. I hope this help somebody.
I have one scenario to send an ajax post request from http to https (have to do that for some complex reasons), and I need to pass credentials for the sake of cookies.
I use Web Api in server side, with NuGet package Microsoft.AspNet.WebApi.Cors to enable Cors request.
The code in client side:
$.ajax({
url: 'https://www.sitename.com/api/xxx',
type: 'post',
data: {
'': 1
},
headers: {
'__AntiXsrfTokenKey': 'whatevertokenhere'
},
xhrFields: {
withCredentials: true
},
dataType: 'json',
success: function (data) {
}
});
Web Api settings:
config.EnableCors();
EnableCors attribute for controller:
[EnableCors(origins: "http://www.sitename.com", headers: "*", methods: "*", SupportsCredentials = true)]
public class XXXController : ApiController
The preflight request header:
Access-Control-Request-Headers: accept, __AntiXsrfTokenKey, content-type
Access-Control-Request-Method: POST
Origin: http://www.sitename.com
The response header:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: __AntiXsrfTokenKey,content-type
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS
Access-Control-Allow-Origin: *
The problem is clearly that Access-Control-Allow-Origin header is returning a wildcard *, instead of the request origin which I specified in the attribute of the controller 'http://www.sitename.com'. So I end up of the error:
A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://www.sitename.com' is therefore not allowed access.
Does any one know why is that behavior and how I can set the Access-Control-Allow-Origin domain correctly in the EnableCors attribute?
Ok, finally found this in web.config within system.webServer
<rewrite>
<outboundRules>
<rule name="Set Access-Control-Allow-Origin header">
<match serverVariable="RESPONSE_Access-Control-Allow-Origin" pattern="(.*)" />
<action type="Rewrite" value="*" />
</rule>
</outboundRules>
</rewrite>
I'm having trouble calling my web api with authentication. It works fine if I leave it out and call methods that don't need authentication.
You guys see anything off in this code?
Here is my ajax call to the server.
jQuery.support.cors = true;
function GetAllPlayers() {
$.ajax({
type: "GET",
url: webServiceUrl + "/api/Player/GetAllPlayers",
beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', 'Bearer ' + $.cookie("fanaTok")); },
success: function (result) {
//TODO handle success
},
error: function (xhr, ajaxOptions, thrownError) {
//TODO Handle error
}
});
}
And here is my web.config
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type, Accept, Authorization" />
<add name="Access-Control-Allow-Methods" value="GET,POST" />
</customHeaders>
</httpProtocol>
Calling to localhost
The error message:
OPTIONS /api/Player/GetAllPlayers 405 (Method Not Allowed)
OPTIONS/api/Player/GetAllPlayers Invalid HTTP status code 405
XMLHttpRequest cannot load/api/Player/GetAllPlayers. Invalid HTTP status code 405
I finally figured out what was wrong.
The web api did not accept OPTIONS call to the server to verify if the custom authentication header was allowed.
I came across an article where this OPTIONS problem is fixed
http://www.jefclaes.be/2012/09/supporting-options-verb-in-aspnet-web.html
It took me a very long time to figure this out, I hope this helps.