i have built website with asp.net webservice where the user can register and login and make ads but the main issue that the webservice is not secured cause i can call it and pass parameters to it in the basic console of the google chrome i can execute webmethod and add user with any role i like without any credentials the code is
$.ajax(
{
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/anywebservice.asmx/AddUser',
data: JSON.stringify({
FullName: $('#txtFullName').val(),
BirthDate: "1/1/1900",
GenderId: $("input:radio[name='rblGender']:checked").val(),
CountryId: $("#ddlCountries").val(),
Email: $('#txtEmail').val(),
Mobile: $('#txtMobile').val(),
RoleName: "Users",
LoginName: $('#txtUserName').val(),
Password: $('#txtPassword').val(),
IsApproved: "true"
}),
beforeSend: function () {
//$('.tableContent').block({ message: null });
//$('.tableContent').spin(opts);
},
complete: function () {
//$('.tableContent').unblock();
//$('.tableContent').spin(false);
},
success: function (data) {
if (data.d < 0) {
CustomAlert(data.d);
}
else {
CustomAlert(window.lang.translate("You have sucssesfully registered"));
}
}
});
of course i know that i can create separated webmethod that does not take role name as parameter but this method is just example i have many methods that i am using for the clients but i need them to be secured not like this or i should separate the admin webservice from the client webservice and if so how can i secure both
Require authentication/authorization on any AJAX request you want to secure.
In your example, add 2 parameters: the LoginName and Password of the user submitting the request. Then perform authentication/authorization on the sever to ensure the user has rights to add a new user. Return a 403 response if they are not authorized.
Related
I wrote a service that converts English to Pig Latin for my website. It's a API endpoint that gets a string posted to it.
I'm concerned that because anything can be sent by the user, unsafe code could somehow be sent and run on the server.
Do I need to sanitize the input under these circumstances?
//Here is the API Action.
[HttpPost]
[ResponseType(typeof(string))]
[Route("api/plconverter")]
public IHttpActionResult TranslateIntoPigLatin([FromBody]string english)
{
string piglatin = convert_to_pig_latin(english);
return Ok(piglatin);
}
//Here is the AJAX call that gets made.
$.ajax({
url: "/api/plconverter",
type: "POST",
data: JSON.stringify(($(this).val().trim())),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#pig_latin_output").html(data);
}
});
I have an application where around 20 http generic handler are used for ajax call.
I have used IReadOnlySessionState for accessing the session in my handlers.Everything is working fine.
But when session expires my handler is returning some html as it redirects to default page and html of default page is sent back in the response.
To overcome this issue.
I have checked the session variable in the handler and if it is null the I have written
context.Response.Write("logout")
And I check in jQuery ajax weather it is logout or anything else.
$.ajax({
url: "myhandler.ashx",
contentType: "application/json; charset=utf-8",
success: function (data) { checklogout(data); $("#loading").hide(); },
error: function () { $("#loading").hide(); },
async: false
});
If it is logout then I have used location to redirect to login page.
I am using form-authentication to authenticate user.
Is there any better approach for checking and redirecting to login page using jquery-ajax call.
You have your handlers in a directory that automatically control by the authentication of asp.net.
What I should do is to not let automatically control by the asp.net authentication by setup that on web.config so the call to the handler will done ether the user is logged in ether not, and inside the handlers I will check for that, if the user that call that handler have the session and the authentication.
Then in the case that the user did not have the authentication to read that handler I return a simple flag to my ajax call, then recognize and make redirect, eg as:
$.ajax({
url: "myhandler.ashx",
contentType: "application/json; charset=utf-8",
success: function (data)
{
if(data.redirectToLogin == true)
{
window.location = "/login.aspx"
}
else
{
// do the rest job
}
},
error: function ()
{
$("#loading").hide();
}
});
On login I want to generate a new SessionId. I have found one solution that works, but it requires some pretty hackish things and requires the app have Full Trust securityPolicy setting.
Is there any other way to achieve this?
Looks like this works:
Session.Abandon();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
By clearing out that cookie, a new session with a new session ID will be created at the server.
(Reference: Microsoft Support)
EDIT: Here's an example using AJAX (with jQuery) to call the server code without a page refresh - it calls twice, once to remove the first session, and once to generate a new one. There may be a better way, but this does work.
function newSession() {
jQuery.ajax({
type: "POST",
url: "WebForm1.aspx/ClearSession",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
jQuery.ajax({
type: "POST",
url: "WebForm1.aspx/NewSession",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () { console.log("Success!"); },
error: function (x, y, z) {
console.log("Failure!");
}
});
},
error: function (x, y, z) {
console.log("Failure!");
}
});
}
And on the code-behind (for WebForms - you could also do this with an MVC controller):
[WebMethod]
public static void ClearSession()
{
HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
}
[WebMethod]
public static void NewSession()
{
HttpContext.Current.Session["x"] = 123;
}
I'm currently considering a configuration-based solution, rather than a code-based one. I would configure either the web server or load balancer to strip away request and response headers containing cookies for just the login page. Remove the "cookie" headers for request headers and "set-cookie" for response headers.
Every request (GET or POST) to the login page will contain no cookie information, thus forcing ASP.NET to create a new session and (more importantly) a new session id.
It's less efficient than forcing a new session creation on login, but the technique could be useful in cases where you cannot modify the code.
I am trying to communicate to database from JavaScript using AJAX.
I have followed one article A beginner’s guide for consuming a WCF service in JavaScript using ASP.NET AJAX to understand about this functionality. I have done everything like exactly shown in the article. But, I couldn't understand how to set up the communication from JavaScript file.
Please note that as per my project requirement I can use only the second technique explained in the article: Using a Service Interface Defined in the Class Library.
Can anybody please suggest me how to do this?
Follow these steps
1) Creat a WCF service in your application.
2) Then add reference to your WCF Service.
3) Then add wcf service to the script manager control of your page
4) Now you can access the wcf service on your page.
Step by Step tutorial using VB.NET
http://v4.ajaxtutorials.com/tutorials/javascript/expose-wcf-service-to-javascript-in-asp-net-4-0-vb/
I used the following JavaScript code to get data from the database over AJAX:
$(function () {
var search = $("#<%=txtAccountNo.ClientID%>");
search.watermark('Enter Account No');
search.autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/") %>AutoCompleteService.asmx/GetAccountNo',
data: "{'prefixText':'" + search.val() + "','count':'10','contextKey':''}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
if (data.d != null) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
}
},
error: function (XMLHttpRequest, textStatus, error) {
//alert(textStatus);
}
});
},
minLength: 1
});
});
I have a web form and I use jQuery/AJAX/JSON to send objects to a web service using:
$.ajax({
type: "POST",
url: "SynchroniseCustomers.asmx/synchroniseCustomers",
data: JSON.stringify(customerObj),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status) {},
success: function (msg) {}
});
From the web service I want to check if the insert into the database was successfull, return a variable with an ID and pass this ID to a function. In the object I have the ID so I could have:
success: function (msg) {deleteCustomer(ID);}
But this only checks if the data was passed to my method in the web service?
I have followed this example
http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/
and in the class Person I get a message back from the database server telling me if the insert was successfull or not so like:
if (successfull)
{
return ID;
}
Is there a way to get this ID back to the web form and use this in a variable?
Thanks in advance.
You want to return a result object with an isSuccess and id property. You can then do the following:
success: function (result) {
if (!result.isSuccess) {
// display friendly error message indicating that the db insert failed
} else {
var id = result.id;
// do client side processing with primary key returned from db insert
}
}
How you return the result object depends on your web services framework (e.g., WCF, MVC, WebMethod, etc.). The framework will serialize your .NET object to a JSON encoded result (e.g., { isSuccess: true, id: '1234'}).
As an example, in ASP.NET MVC you simply return a JsonResult using Json.(MySerializableResult). If you post what you are using for web services, I'm sure you'll get a specific answer to that framework.