2sxc CustomWebApi enable CORS - asp.net-web-api

I create my custom webapi inherited from SxcApiController,
but when I try to use this api from diferent domain I get message:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have this attributes in my controller method:
[HttpPost]
[DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.Anonymous)]
I call my method this way:
$.ajax({
url: apiurl,
type: 'POST',
//headers: {
// 'Access-Control-Allow-Origin': '*'
//},
//crossDomain: true,
dataType: 'json',
data: data,
success: function (d) {
debugger;
alert("Saved Successfully");
},
error: function (d) {
debugger;
alert("Error please try again");
}
});
if I enable crossDomain and add header the error is changed to:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I think that SxcApiController is inherited from DNN Api Controller and also don't know how to enable CORS on DNN
What else I am missing to enable CORS for this method?
============== edit 1 ================
I added this to web.config where api is hosted:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
and now the error is:
401 (Unauthorized)
What else I am missing?
============== edit 2 : Now is OK ================
I added this attributes in my method and now is OK:
[HttpPost]
[AllowAnonymous]
[DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.Anonymous)]

Perfect, sounds like you got it to work + it wasn't actually a CORS issue.
Just as some additional information: in case you really want to enable CORS with authentication for other domains, you'll need to go deeper because in that scenario the browser will do a pre-flight to really check if it's allowed to include authentication & cookies in the request. That is something that IMHO DNN doesn't provide, and you'll have to enable it using asp.net magic - basically by either creating a special request-handler for the preflight, or using asp.net header rewrites in web.config.

Related

Avoid CORS in rest API

I'm having a problem to make a call to a rest API.
In the document (FAQ) of the web application there is an example that use AJAX request to make the call. Here an example:
var url = 'https://example.com/yyy';
$.ajax({
type: 'POST',
url: url,
cache: false,
data: {
opt: JSON.stringify(example)
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result)
{
console.log(result);
} });
I created a local page with this code to made the post to the API that is located on a remote server but I receive an error about CORS.
Is there any solution to circumvent this problem? I tried to use firefox plugin to allow CORS but it didn't solve the problem. The session is authenticated via form before use the endpoint.
I see several issues:
Try to run the code from a domain and not from local disk (alternatively you can consider using https://crossorigin.me/ )
How does the authentication work? if with cookies you need to add withCredentials to the ajax request.
Make sure the API returns Access-Control-Allow-Origin: foo header where foo is the domain your code runs in. If you also used withCredentials, you should add Access-Control-Allow-Credentials: true

Facebook graph api Request header field authorization is not allowed

I'm calling facebook graph api using ajax as follows,
$.ajax({
url: "https://graph.facebook.com/oauth/access_token?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&grant_type=fb_exchange_token&fb_exchange_token="+accessToken,
type: 'GET',
contentType: "application/json",
success: function (response) {
},
error: function (error) {
console.log('Error occurd while retrieving long live access token');
}
});
But it shows error as follows,
Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
If I make the request using postman or using the browser it works fine. Appriciate any help to resolve this issue. I tried several answers regarding the Access-Control-Allow-Headers in the server side, but in this case I don't have the control over facebook side.

Tibco Spotfire basic authentication with cross domain ajax call

I am creating a client side session using cross domain ajax call to Spotfire server. For authentication I am using basic authentication method. When I make my request through Postman with Authorization header and value 'Basic ' + btoa('user:password') it send correct header and start a new session, whereas in web browser it shows error as
NetworkError: 405 Method Not Allowed -
http://server-path/GetJavaScriptApi.ashx?Version=8.0
&
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
http://server-path/GetJavaScriptApi.ashx?Version=8.0.
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
This was because in cross domain ajax call first OPTIONS request is made followed by POST/GET, to overcome this I made dataType: "jsonp" in my ajax call. Now GET calls are working but now gives me a new error:
The resource from
“http://server-path/GetJavaScriptApi.ashx?Version=8.0&callback=jQuery111107482621169238032_1487159470493&_=1487159470494”
was blocked due to MIME type mismatch (X-Content-Type-Options:
nosniff).
Ajax code is as follows:
$.ajax({
url: 'https://server-path/GetJavaScriptApi.ashx?Version=8.0',
type: 'GET',
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", Basic ' + btoa('user:password'));
xhr.setRequestHeader("content-type", 'text/plain');
xhr.setRequestHeader("X-Content-Type-Options", "nosniff");
},
dataType: "jsonp",
success: function (jsonData) {
console.log(jsonData);
},
});
Call to https://server-path/GetJavaScriptApi.ashx?Version=8.0 return javascipt as response after successful authentication
Please help to resolve.. Thanks

how to use ajax to trigger jenkins job build?

I'm writing a web page to let others can trigger the some jobs' build with parameters in jenkins. So I use ajax to send POST request:
var urlString = "http://localhost:8080/job/myjob/buildWithParameters";
$.post(
urlString,
{myParam:"there is some data"},
function(data)
{
alert(data);
},
"json"
);
But I got Http 403 response:
XMLHttpRequest cannot load http://localhost:8080/job/myjob/buildWithParameters. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 403.
I know the cross site problem , but I cannot search any helpful information from Google, can ajax do this job?
UPDATE:
I found a similar question
So I update my code to :
$.ajax({
type: "POST",
url: urlString,
dataType: 'jsonp',
data: {},
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "Basic " + btoa("admin:123456"));
},
success: function(data) {
},
complete: function(xhr, statusText){
}
});
I can confirm the username and password is correct , but I got 405 Method Not Allowed. Is there anything wrong?
Put your web page in the userContent folder under $JENKINS_HOME directory. Then open $JENKINS_URL/userContent/yourwebpage.html in your browser. Now the javascript in the page is loaded from the same origin where ajax calls will go, so it should be allowed without CORS tricks.
Jenkins want a POST not a GET HTTP request, a JSONP request is a GET: you can't do that :D
You can try to do in these way:
Startup jenkins with the AJP binding as described here
Configure Apache2 httpd as a reverse proxy for the Jenkins AJP
Force in Apache2 response header as described here to enable CORS
At the end you can use directly POST instead of JSONP.
have fun with XSS :D

Can't retrieve my x-api-key from my request header with CORS enabled. Why?

I'm working with CodeIgniter2 Rest API and AJAX to make requests from a smartphone with PhoneGap to a AWS server with apache.
Everything was working fine when working on my localhost/browser.
But when trying to set up a distant server things got bad.
I have configured my server properly with CORS so that it allows external requests as explained here :
http://dev.nuclearrooster.com/2011/01/03/cors-with-apache-mod_headers-and-htaccess/
To secure the API, I have been setting up an API KEY that I have to pass in the header of my request like so:
$.ajax({
type:"GET",
url: server_url + 'user/available',
headers: { 'X-API-KEY': key },
dataType: 'json'
});
But then, after seeing my ajax called being refused because of an invalid API Key, I have been trying to make sure the server received the key. and it doesnt. when I try to echo my key, its empty.
I can see in my debug console the following:
Request header field X-API-KEY is not allowed by Access-Control-Allow-Headers.
So I have been modifying my .htaccess following this post:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type, x-api-key"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
so now, the message is gone but the problem still remains the same ... why ?
How can I transmit this X-API-KEY through my AJAX call Header so I can authentificate my users ?
Many Thanks
I faced this problem and with weeks of tweaking I was able to get it to work with a hack of a job... I can't remember the exact part that did fix it but will provide with what I am currently using.
Server Side
function __construct(){
parent::__construct();
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("Access-Control-Allow-Headers: X-API-KEY");
}
function available_options(){
$this->response(array('response' => array()), 200);
}
Client Side
function sendData(dataToSend, successCallback) {
window.default_headers['X-API-KEY'] = '_KEY_';
return $.ajax({
type: "POST",
url: server_url + 'user/available',
data: { data : JSON.stringify(dataToSend) }, // serializes the form's elements.
dataType: 'json',
headers: window.default_headers,
xhrFields: {
withCredentials: true
}
});
}
Since you're using a GET request, possibly using JSONP would be of more use, this avoids cross domain requests.
JSONP Request
$.ajax({
type : "GET",
dataType : "jsonp",
url: server_url + "user/available?callback=?", // ?callback=?
success: function(data){
// do stuff with data
}
});

Resources