Partial View loading using javascript : Possible XSS by HP FORTIFY - html

I have a js function , which Fortify identified as XSS vulnerable as below. Can you suggest any solution for this since the method is intensively used in my app.
I am here trying to call a partialview in ajax and the result html am appending to a specified dom div
My function look like the below
function loadPartialViewToDiv(div, obj, api) {
try {
const myUrl = new URL(window.location.origin + api); // always local URL only
$.ajax({
url: myUrl ,
data: obj,
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
if (data != undefined && data != null) {
$('#' + div).html(data);
}
}
});
} catch (e) {
('#' + div).html('Error');
}
}

The dynamic DOM element id was the issue ($('#' + div).html(data); ), we fixed it using two methods
giving a static id. $('#abcd').html(data);
OR
change as $('#' + div).text($(data));

Related

Append additional HTML result in calling MVC action by Ajax in DNN8

I'm new in DNN development.
I have created a very simple module in Visual studio--- A textbox and a button.
I just want to call the action in a controller by click the button, then show the return result in the textbox.
The code call the action success, but not sure why append lots of HTML inforation in the result.
Here is the action in the controller:
public ActionResult test1()
{
return Content("Return something");
}
Here is the Ajax code from the View:
$(document).ready(function () {
$("#btnSub").click(function () {
//alert(this.action);
$.ajax({
type:"GET",
contentType:"application/text",
url: "#Url.Action("test1", "Sky")",
data:"",
dataType: "text",
success: function (data) { $("#txtResult").val(data); alert("Success!") },
error:function(){alert("Failed!")}
});
});
});
And here is the result show in the textbox:
Anyone can let me know why the HTML information returned? Actually, I don't need it.
Thanks
Unfortunately, as described in DNN8 MVC unsupported features, it's not yet possible to return a JsonResult. So the solution I used is to return an ActionResult (although the function returns Json):
public ActionResult Test()
{
return Json(new { success = true });
}
On jquery side, I setup ajax call to receive result as html. This avoid the browser to display a parsing error. Finally, just need to remove the html part and manually parse the response. It's not very clean, but the only solution I found until DNN support JsonResult.
$.ajax({
url: '#Url.Action("Index", "Contact")',
type: 'POST',
dataType: 'html',
data: $('#contact-form input').serialize(),
success: function (response) {
jsonPart = response.substring(0, response.indexOf("<!DOCTYPE html>"));
var data = JSON.parse(jsonPart);
if (data.success) {
alert("Great");
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error!");
}
});
EDIT : Improved solution
DNN8 now support IMvcRouteMapper. You can then register a route in RouteConfig.cs. Once done, you can call the function using following URL :
/DesktopModules/MVC/ModuleName/Controller/Action
The action can return a JsonResult. But pay attention, if you just call that function, it will fail with a null exception on ModuleContext. You have to include in the ajax call the following header :
headers: {
"ModuleId": #Dnn.ModuleContext.ModuleId,
"TabId": #Dnn.ModuleContext.TabId,
"RequestVerificationToken": $("input[name='__RequestVerificationToken']").val()
}
You can find the module complete code here.
This is a working ajax call in DNN 9. You dont have to use #urlaction it will give whole html as well as data. dnn.getVar("sf_siteRoot", "/") +
"DesktopModules/MVC/ModuleName/Controller/Action", this does the trick and don't forget to add the header otherwise it will throw 500 error.
$.ajax({
url: dnn.getVar("sf_siteRoot", "/") +
"DesktopModules/MVC/ModuleName/Controller/Action",
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: "{ 'id':" + JSON.stringify(3543)+" }",
headers: {
"ModuleId": #Dnn.ModuleContext.ModuleId,
"TabId": #Dnn.ModuleCon`enter code here`text.TabId,
"RequestVerificationToken":
$("input[name='__RequestVerificationToken']").val()
},
success: function (response) {
debugger;
},
error: function (errmsg) {
alert("Error!");
}
});
Your controller should be
[HttpPost]
public ActionResult ActionName(int id)
{
var data = id;
return BuidJsonResult(true,data);
}
Happy Coding :)

parameter passing from CDE to PDI pentaho

I have a scenario to pass parameters from pentaho cde using kettle to pentaho data integration and then update the table using the passed parameter in PDI. How can i pass the parameter and get the passed parameter in PDI?
Thanks in advance!!!
You will need to use the Pentaho plugin builder, SPARKL.
With it you can upload a transformation as a callable endpoint and use a CDE dashboard to call it.
First of all, you need a transformation that expects parameters. You can try it with a test one before going to a more advanced transformation:
Example:
defining a parameter and fetching with a Get Variables step
Second you will create a new plugin on SPARKL.
Sparkl welcome screen
Give your plugin a name and add a kettle endpoint to it. If you now look at your pentaho-solutions/system folder, you will have a new folder with the plugin name. Open it and find the ktr file inside the subfolders to replace it with your transformation.
The last step is to add a new dashboard to your plugin and edit it. If you go to the datasources tab now, notice the datasources with 'endpoint' in the name. We will access them by code, but is good to know they are here so you can read data from it too, not just input data.
add a new resource of javascript to your CDE layout with the following code:
var myPluginName = {};
(function(myself) {
myself.runEndpoint = function (pluginId, endpoint, opts) {
if (!pluginId && !endpoint) {
Dashboards.log('PluginId or endpointName not defined.');
return false
}
var _opts = {
success: function () {
Dashboards.log(pluginId + ': ' + endpoint + ' ran successfully.')
},
error: function (){
Dashboards.log(pluginId + ': error running ' + endpoint + '.')
},
params: {},
systemParams: {},
type: 'POST',
dataType: 'json'
}
var opts = $.extend( {}, _opts, opts);
var url = Dashboards.getWebAppPath() + '/plugin/' + pluginId + '/api/' + endpoint;
function successHandler (json) {
if (json && json.result == false) {
opts.error.apply(this, arguments);
} else {
opts.success.apply( this, arguments );
}
}
function errorHandler () {
opts.error.apply(this, arguments);
}
if (endpoint != 'renderer/refresh' ) {
var ajaxOpts = {
url: url,
async: true,
type: opts.type,
dataType: opts.dataType,
success: successHandler,
error: errorHandler,
data: {}
}
} else {
var ajaxOpts = {
url: url,
async: true,
type: 'GET',
dataType: opts.dataType,
success: successHandler,
error: errorHandler,
data: {}
}
}
_.each( opts.params , function ( value , key) {
ajaxOpts.data['param' + key] = value;
});
_.each(opts.systemParams , function (value , key) {
ajaxOpts.data[key] = value;
});
$.ajax(ajaxOpts)
}
})(myPluginName);
You can change myPluginName with whatever you want but that enables you to call that endpoint sending parameters with any button. To do so you can use that code:
myPluginName.runEndpoint(
'myPluginName', // Plugin identifier.
'endpointName', // Put your endpoint name here!
{
params: {
'EXAMPLE_PARAMETER' : foo_bar
},
success: function() { Dashboards.fireChange('refresh', 1); alert('data sent'); },
error: function() { alert('Ops, something went wrong. Check the logs.'); }
})
You can keep track of the execution by monitoring the bi-server logs.
More information on the sources:
Diethard Steiner - Blog
Francesco Corti - Blog
Follow these guys, they are amazing.
You could do that, or you could just create a CDA data source, which takes a parameter as defined in your transformation.
Params are passed to CDA via the usual &paramYOURPARAMNAME=x syntax on the URL.
In the transformation you get the parameter using the get variables step.
Did I miss something?

Not able to get external API data through JQuery

I am trying to get external REST API data through JQuery, but it returs undefined. But when I use my local REST API url, it works. Can anybody explain whats is the problem. Any code sample will be appreciated.
This how i am accessing external Rest API via JQuery.
function GetCompanyName(id) {
jQuery.support.cors = true;
$.ajax({
url: 'http://novacompanysvc.azurewebsites.net/api/companies' + '/' + id,
type: 'GET',
dataType: 'jsonp',
success: function (data) {
WriteResponse(data);
},
error: function (x, y, z) {
alert("company" + x + '\n' + y + '\n' + z);
}
});
}
result is XML so you need to set dataType: "text/xml" and then parse it:
success: function (data) {
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(data,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(data);
}
I tried to test this but I got: is not allowed by Access-Control-Allow-Origin that is same-origin restriction so make sure you have access to this API or you will have to do it on the server using CURL in PHP for example.
Your are getting id variable in the function you showed in your question, but you are no using it,
if you want to send it add:
,data:{ id:id }
Request should look something like this:
function GetCompanyName(id) {
jQuery.support.cors = true;
$.ajax({
url: 'http://novacompanysvc.azurewebsites.net/api/companies',
type: 'GET',
data:{ id:id },
dataType: "text/xml",
success: function (data) {
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(data,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(data);
}
WriteResponse(data);
},
error: function (x, y, z) {
alert('error');
}
});
}

Unable to recieve JSON from Webmethod using $.getJSON or Ajax call

I have some JSON objects that I want to process on Client Side, but My WebMethod that I specified does not want to fire.
Here is the Ajax and GetJson methods i used in my Client Side Script:
GetSJON
$(document).ready(function() {
$(document).ready(function() {
//attach a jQuery live event to the button
$('#getdata').live('click', function() {
$.getJSON('/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions', function(data) {
//alert(data); //uncomment this for debug
// alert(data.item1 + " " + data.item2 + " " + data.item3); //further debug
$('#showdata').html("<p>item1=" + data.item1 + " item2=" + data.item2 + " item3=" + data.item3 + "</p>");
});
});
});
Here is the Ajax
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
success: function (res) {
$('#Results').append(CreateTableView(res)).fadeIn();
}
});
});
Both of these Methods Call StockPlacementOptions which is my WebMethod that look like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json,
UseHttpGet = true, XmlSerializeString = false)]
public static List<StockReturnMethod> StockPlacementOptions()
{
scmEntitiesPrimaryCon entities = new scmEntitiesPrimaryCon();
var binOptions = (from avail in entities.ProductAvailibleBins(1, 2)
select new StockReturnMethod() { LotID = (int)avail.LotID, LotName = avail.LotName, AreaID = (int)avail.AreaID, AreaName = avail.AreaName, BinID = (int)avail.BinID, BinName = avail.BinName }).ToList();
return binOptions;
}
If I can just get the JSON web Method to fire on $(document).ready event, I will be able to process and work with the data from there. I have also tried looking at a diffrent jQuery library like KnockoutJS with it's data processing capability, also no luck.
I am using ASP Webforms on Framework 4 with Html5 Markup.
Any advice will be greatly appreciated.
Why are you using two document.ready() handlers at your client side getJson and ajax
$(document).ready(function() { // <-------you can remove this handler
$(document).ready(function() {
$('#getdata').live('click', function() {
$.getJSON('/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions', function(data) {
//alert(data); //uncomment this for debug
// alert(data.item1 + " " + data.item2 + " " + data.item3); //further debug
$('#showdata').html("<p>item1=" + data.item1 + " item2=" + data.item2 + " item3=" + data.item3 + "</p>");
});
});
}); // <-------you can remove this handler
although i am not sure this could be the issue but try this one if this helps.
I got it fixed by using a combination of KnockoutJS and ajax.
By utilizing the knockoutJS mapping model, I am able to manipulate the returned JSON anyway i want :)
Here is my Jquery that does the Mapping and obtains JSON from server.
<script type="text/javascript">
//Declareing Viewmodel For KnockoutJS
var viewModel;
//Using Mapping Plugin for Knockout JS
function bindModel(data) {
viewModel = ko.mapping.fromJS(data);
console.log(viewModel);
ko.applyBindings(viewModel);
}
//Onload ObtainJSON
$(document).ready(function () {
$.ajax({
url: "WebForm1.aspx/StockPlacementOptions",
// Current Page, Method
data: {},
// parameter map as JSON
type: "POST",
// data has to be POSTed
contentType: "application/json",
// posting JSON content
dataType: "JSON",
// type of data is JSON (must be upper case!)
timeout: 10000,
// AJAX timeout
success: function (result) {
bindModel(result);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
});
</script>
I also changed the Webmethod slightly to obtain the result i wanted:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<StockReturnMethod> StockPlacementOptions()
{
scmEntitiesPrimaryCon entities = new scmEntitiesPrimaryCon();
var binOptions = (from avail in entities.ProductAvailibleBins(1, 2)
select new StockReturnMethod() { LotID = (int)avail.LotID, LotName = avail.LotName, AreaID = (int)avail.AreaID, AreaName = avail.AreaName, BinID = (int)avail.BinID, BinName = avail.BinName }).ToList();
return binOptions;
}
And That's it :D
Thanks for all the help

Calling service from Html

i want to call asp.net web service from java script and pass the parameters to it .is there any code sample or demostration that will help me to acheive that??
thanks in advance
JQuery:
function AddLocation(ParentID) {
$.ajax({
type: "POST",
url: "../server.asmx/Save",
data: "{'ID':'0','ParentID':'" + ParentID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var item = document.createElement('option');
item.value = data.d.split("$")[0];
item.text = name;
//do stuff
}
});
}
jQuery supports this behavior. you can use jQuery to do the ajax call as show below. this method has two call back functions for success and for failure.
function loadData()
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: 'methodurl',
success: methodSuccedded,
error: methodFailure
});
}
function methodSuccedded()
{
//do your logic.
}
function methodFailure()
{
//do your logic.
}
You can do so, using AJAX, and get the response from the server as an JSON object.
var xmlHttp = new ActiveXObject("Microsoft.XmlHttp");
var url = "Service1.svc/ajaxEndpoint/";
url = url + "Sum2Integers";
var body = '{"n1":';
body = body + document.getElementById("num1").value + ',"n2":';
body = body + document.getElementById("num2").value + '}';
// Send the HTTP request
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send(body);
// Create result handler
xmlHttp.onreadystatechange= function X()
{
if(xmlHttp.readyState == 4)
{
result.innerText = xmlHttp.responseText;
}
}
Getting the response as JSON would help you evualte it asn object and u can act on it through JavaScript.
See these links for reference:
http://blogs.msdn.com/b/alikl/archive/2008/02/18/how-to-consume-wcf-using-ajax-without-asp-net.aspx
http://dotnetslackers.com/articles/ajax/JSON-EnabledWCFServicesInASPNET35.aspx
The below link is a pretty decent method from my experience.
http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/