How can I send javascript as a string in a JSON parameter - javascript

I am building dynamic javascript in C# and sending it back to a single page application in a JSON request.
The problem is, the javascript/jquery in the JSON parameter breaks the JSON. How do I properly escape this?
Here is the code... it will combine many small segments of js from files into a string and inject it into a page.
Many thanks!
try
{ // Open the text file using a stream reader.
using (StreamReader sr = new StreamReader("dynamic.js"))
{
// Read the stream to a string, and write the string to the console.
dynamicJS = sr.ReadToEnd();
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
// user has been authenticated return data and JS to the front end
return $"{{ \"Email\": \"{userDetails.Email}\", \"DisplayName\": \"{userDetails.DisplayName}\", \"Services\": {safeServices.SerializeToJsonString()}, \"PageElements\": \"{pageURLs}\", \"DyanamicJS\": \"{dynamicJS}\" }}";

Related

cefsharp ExecuteScriptAsync(json) uri too long

I am using cefSharp in my winForm application.
I want to pass a long json from my winform to the html page displayed by the cefSharp.
I tried to write the following:
Private WithEvents m_chromeBrowser As ChromiumWebBrowser
...
CefSharp.Cef.Initialize()
page = New Uri("www...")
m_chromeBrowser = New ChromiumWebBrowser(page.ToString)
Panel.Controls.Add(m_chromeBrowser)
...
Dim json as String = "[{code:1,name:a,val:0},{...}....]"
m_chromeBrowser.ExecuteScriptAsync("functionName('" & json & "');")
But I keep getting the following error:
Request-URI Too Long
Do you have any idea how to pass long json from winform to browser.
Thanks
Well, you would be better off exposing a .Net class to JavaScript by registering an AsyncJSObject, execute the class method from JavaScript and parse the return result.
Something like this:
public class CallbackObjectForJs {
public string getJson() {
return myJsonString;
}
}
... then register the class:
_webBrowser.RegisterAsyncJsObject(
"Browser",
new CallbackObjectForJs(),
BindingOptions.DefaultBinder);
... and finally call the method from Javascript and use a promise to get the result:
Browser.getJson().then((result) => {
var myJsonString = JSON.parse(result);
console.log(myJsonString);
});
You can read more about it here:
https://github.com/cefsharp/CefSharp/wiki/General-Usage#3-how-do-you-expose-a-net-class-to-javascript
Hope it helps!

URL GET using Basic Auth with Java Servlet

I have a .jsp page which handles some basic html (text field, submit button a table to populate) and javascript. On click it calls my java Servlet class which handles the request and the response from and to the jsp respectfully. I also have a Java class to handle url connection to make a REST call using GET which should return a json string result. This is the scenario: User wishes to make a simple search by entering an ID value to populate the table using REST to connect to a url and get a json response.
I have separately tested the Java class to make a REST call made by URL connection with Basic Authentication to GET the data in json string and it works perfectly fine. (I have coded 4 different methods of doing this and all work fine and return the expected json).
I have separately tested the jsp page making a call to the servlet to populate "dummy" values in the table and the servlet response is fine and the table populates as expected.
THE PROBLEM:
When I tried to populate the table by the values obtained from the GET REST call, it hangs and I get no result. So I tried to investigate why and found out that for some crazy reason, the servlet doesn't like the line of code which sets the header with the basic authentication to get access to the URL. I tried commenting the basic auth 1 line code out (to debug, so now we have no authentication) but passing through some "dummy" hard coded data, and it populates the table.
I actually don't know why the servlet doesn't like it when I set the authentication. My guess is probably it is overwriting the servlet's response path and therefore lost the initial response location to the jsp? (i.e. where to send the json back to?) Can anyone help me here? Anyone know whats happening? is my assumption of the problem correct? if so, how do I overcome this problem?
Javascript call to the servlet:
$("#myForm2").submit(function(e) {
$.ajax({
type: "GET",
url: "servlet1", // the script where the form input is handled.
data: $("#myForm2").serialize(), // serializes the form's elements.
success: function(responseData){
var dataObj = $.parseJSON(responseData)
$('#myTable').append(>>add values to table here<<);
});
e.preventDefault(); // avoid to execute the actual submit of the form.
$("#myForm2")[0].reset(); // clear previous values entered
});
Servlet class, request made by jsp page and the servlet's response:
Rest getCallOnURL = new Rest(); // instance of my rest class
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException {
// create a dummy string "test" to hold the ID value passed in from javascript
String testID = request.getParameter("ID");
// Hard coded - only for testing purposes
if (testID.equals("1")){
//call my java class' method to connect to url and retrieve the json string
getCallOnURL.connectToUrlAndMakeAGetRequest();
valueToPopulateTable = getCallOnURL.testJsonString;
}
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
// using backslash to escape the quotes to make a valid json response
out.print("{\"testRow\": \"valueToPopulateTable\"}");
out.close();
}
My Java Class method to make URL call and Basic Authentication:
String testJsonString = "defaultValue";//testing purposes
//creates a valid encoded authentication string
private String basicAuth(String name, String pass){
String authString = name + ":" + pass;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
return authStringEnc;
}
private HttpURLConnection prepareGETConnection(final URL verifierURL)
throws IOException {
final HttpURLConnection connection = (HttpURLConnection) verifierURL.openConnection();
connection.setRequestMethod("GET");
//this is the line which authorizes access to the url via Basic Auth
connection.setRequestProperty("Authorization", "Basic " + basicAuth(name, password));
return connection;
}
public void connectToUrlAndMakeAGetRequest(){
try {
String webPage = "URL HERE";// pass it a valid REST url with endpoints
URL url = new URL(webPage);
HttpURLConnection conn = prepareGETConnection(url);
// get the url response json string
InputStream getUrlresponse = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(getUrlresponse));
//get only the first line of the string - testing purposes only!
testJsonString = rd.readLine();
rd.close();
conn.disconnect();
} catch(IOException e){
System.out.println("IO exception: "+e);
}
}

recieving broken JSON data in javascript

I have PageMethod in javascript which is receiving JSON data from C#.
In C# its getting full xml data from database and converting into JSON and sending back to PageMethod.
JSON Converted data is about 33kb, but i'm not able to receive full data in javascript. I'm receiving only 9 kb of data. any solution for getting full data in java script.
PageMethod.methodName(onSuccess,OnFail);
function OnSuccess(result)
{
alert(result);
}
function OnFail()
{
alert("Error");
}
C# code as follows,
ParamResult objParamResult = new ParamResult();
objParamResult.ResultDt = string.Empty;
DataTable XmlMainSub = objCBTag.getParamPickupDetailsDB();
string myData = XmlMainSub.Rows[0][0].ToString();
XmlDocument doc = new XmlDocument();
doc.LoadXml(myData);
string jsonText = JsonConvert.SerializeXmlNode(doc);
return jsonText;
instead of
string jsonText = JsonConvert.SerializeXmlNode(doc);
you can use
string jsonText = new JavaScriptSerializer().Serialize(doc).toString();
you need to use namespace for this
using System.Web.Script.Serialization;
After i made lot of research, i found that its not possible to send JSON data from C# to javascript which is more than 8KB or 9KB in size.
And i solved this problem by making use of c# generics which is Dictionary which contains Key and Value Pair. I Tried to loop XML Data which is coming from database and stored in a dictionary object.
Then i passed it to javascript. There i able to receive full data without any error.

Should I use JSON econding, JavaScript encoding or both?

I’ve started to work with security of a website and my task is to prevent XSS attack. I’ve seen the OWASP rules to deal with it. However, I am not sure about which of these rules I should use on my specific case.
I have the following .jsp file:
<%
// Get Requests
InputData data = new InputData(request);
int idBcomp = data.getInt("bcomp");
Bcomp bcomp = new Bcomp();
BcompDao bcompDao = new BcompDaoImpl();
bcomp.setId(idBcomp);
JSONObject json = new JSONObject();
try {
for (Bcomp s : bcompDao.find(bcomp)) {
json.accumulate("id", s.getId());
json.accumulate("nome", s.getNome());
json.accumulate("nox", s.getNox());
}
} catch (SQLException e) {
json.accumulate("erro", e.getMessage());
} catch (Exception e) {
json.accumulate("erro", e.getMessage());
}
out.write(json.toString());
%>
I also have the .js file that receives and manipulates the JSON created by the file above. In this file I have the following code:
function import(idBcomp) {
$.ajax({
url: 'ajax/bcomp.jsp',
data: {bcomp: idBcomp}
}).done(function (r) {
var obj = $.parseJSON(r);
$("#nome").val(obj.nome);
$("#nox").val(obj.nox);
$("#id_bcomp").val(obj.id);
});
}
Therefore, my question is: Should I use javascript encode, JSON encode or both? And where should I do the encoding?
I am using OWASP XSS API for encodeForJavaScript and JSON encoding
JSON encoding. JSON indicates to the browser that the content is DATA ONLY and should not be executed. JavaScript encoding indicates a potentially executable bundle.

Send JS object to JSP page [duplicate]

This question already has answers here:
Call Servlet and invoke Java code from JavaScript along with parameters
(3 answers)
Closed 6 years ago.
I have a JS object in a JavaScript file. I have to pass this object to a JSP page. The page picks up this object and processes it. How can I do it?
The same way you get any other data from a web browser to an HTTP server.
Encode it in an HTTP request by submitting a form / setting the window location / using XMLHttpRequest / etc.
There are a couple of issues you need to resolve first, are you doing this in an AJAX style of request? is this a form submission? is there going to be on-going interaction within the page-session between the client/server passing JSON objects back-and-forth?
Lets tackle the simple case of a form submission, once you get that you should be able to get the remaining cases going as they are just "extensions" of this base case. Say you have some form that will submit the data in some field:
<form name='my_form' id='my_ford_id'>
<input type='hidden' name='my_input_field' />
</form>
then at some point in time you have a piece of code that executes and you have your JSON object
function myFunction() {
var json_data = getJsonData();
document.forms['my_form']['my_input_field'].value = json_data;
document.forms['my_form'].submit();
}
You will then on the JSP side receive this data as a JSON string inside of a form field, at which point you need to process it, lets assume you have some kind of a JSON library available to you, the code might look something like this:
<%
String myInputField = request.getParameter("my_input_field");
if(myInputField != null) {
try {
JSONObject myObject = new JSONObject(myInputField);
}
catch(JSONException e) {
}
}
%>
If you need an "AJAX" style of interaction, you will be making a number of such requests in the page, but fundamentally it falls back to the original problem of submitting the data. Since you are using forms in this example, and JSP, you don't have to worry at any point about encoding, the browser/server will take care of things for you.
When you send json object the servlet receive it in the same way of receiving data sent by submitting the form, for example, if you send a variable "action" with value="getCountries"
var option = {
"action": "getCountries"
};
$.getJSON('YourServlet', option, function() {
//hadle the result returned by servlet
});
The defualt method is GET, in the servlet you handle the request as you handle a normal request
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if (action != null) {
if (action.equals("getCountries")) {
List coutries = getAllICountries(request); //get the countries
String json = new Gson().toJson(coutries);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().write(json);
return;
}
}
}
Notice how we return the result from servlet to javascript, we return a json object.
"JSON" Site helps you to manage Json Objects in JSp/java.
You have to convert the string obtained from javascript to a json object.Then manage it easily.

Categories

Resources