Getting "401 Unauthorized" error consistently with jquery call to webmethod - asp.net

I have been struggling to get my jquery call to a webmethod to work. I am being bounced by the server with a "401 Unauthorized" response. I must have an incorrect setting in the web.config or somewhere else that would be preventing a successful call.
Your insight is appreciated!
Call to js function the invokes the jquery call
button.OnClickAction = "PageMethod('TestWithParams', ['a', 'value', 'b', 2], 'AjaxSucceeded', 'AjaxFailed'); return false;";
JavaScript function that makes the jquery call
function PageMethod(fn, paramArray, successFn, errorFn) {
var pagePath = window.location.pathname;
var urlPath = pagePath + "/" + fn;
//Create list of parameters in the form:
//{"paramName1":"paramValue1","paramName2":"paramValue2"}
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
//Call the page method
$.ajax({
type: "POST",
url: pagePath + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
timeout: 10000,
dataType: "json",
success: function(result) { alert('Overjoyed'); },
error: function(result) { alert('No joy'); }
});
}
Web method in page
public partial class WebLayout : System.Web.UI.Page
{
[WebMethod()]
public static int TestNoParams()
{
return 1;
}
[WebMethod()]
public static string TestWithParams(string a, int b)
{
return a + b.ToString();
}
...
Response as seen in Firebug console
json: {"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}
and
"NetworkError: 401 Unauthorized - http://localhost/Care-Provider-Home/Profile/Personal-Profile.aspx/TestWithParams" TestWithParams
I have looked at and read the usual sites on the subject (Encosia, et al), but to avail. Either I am missing a critical piece, or there are some subtleties in the security parameters of my environment that preventing a call.
Here are some other potentially useful tidbits that may impact your diagnosis:
Webmethods in codebehind
Using Sitecore CMS (Does not seem to intefere, never know)
IIS7
.NET 3.5
jQuery 1.3.2
I look forward to your insights and direction--thank you!

Yes, it did get working! Since Sitecore CMS does perform URL rewriting to generate friendly URLs (it assembles the pages in layers, dynamically, similar to Master Page concept), it occurred to me that it may be causing some problem the initially caused the 401 error. I verified this by creating a separate project with a single ASPX--and with some work I was able call the web methods and get values using the jquery. I then created nearly identical ASPX in my web root, but told Sitecore to ignore it when a request is made to it (IgnoreUrlPrefixes in the web.config), after some work I was able also get it to work successfully! Thanks for your help.

The json response from the Firebug Console provides the most telling clue IMO. The System.InvalidOperationException (which strangely rides on a 401 response) suggests something more is at work.
First, googling on "InvalidOperationException webmethod jquery" returns articles which suggest serialization problems can throw this exception. To rule this out, temporarily change "data: paramList" to "data: '{}'". In addition, attach a debugger and see if the exception happens before the method executes or after it completes and attempts to serialize the result.
If the steps above come up empty, you may want to try resetting to a clean web.config or read more of the results that come back from the "InvalidOperationException webmethod" search

What form of authentication are you using, if any? The first thing that comes to mind is to make sure that your webApp in IIS is set to allow anonymous users (if you indeed desire to make the call as an anonymous user). Also that your Authentication mode in web.config is not set to Windows by mistake. If you cannot allow anonymous users and are using forms authentication, then the user will have to be logged in before this call is made from your page.
If the above are properly set, then try making a regular call to the service from server side to make sure the problem is consistent regardless of the point of invocation of the service.
Post more settings if the problem is not resolved. Hope this helps.

Related

How to call node.js REST API from .NET

If I put the jquery code below within the script tag within a html page and drag the html page into a web browser the call to the API specified in the URL is made and I get back a response in JSON format. So this works good.
The reason I want to use .NET for calling the rest API that is made in node.js is because I want to use the unit test utility that exist in visual studio.
So when I start the unit test the call to the REST API made in node.js should be made and then I can check whatever I want in the returned json format by using the assert.AreEqual.
I have googled a lot and there is several example about
Unit Testing Controllers in ASP.NET Web API 2 but I don't want to unit test controller. I only want to call the REST API(made in node.js) when I start my unit test.
I assume to use .NET in the way I want is probably quite rare.
If it's not possible to use .NET and unit test in the way that I want here
I will use another test framework.
I hope to get some help from here.
Hope you understand what I mean.
$.ajax({
type: 'GET',
url: 'http://10.1.23.168:3000/api/v1/users/1',
dataType: 'json',
async: false,
headers: {
'Authorization': 'Basic ' + btoa('DEFAULT/user:password')
},
success: function(response) {
//your success code
console.log(response);
},
error: function (err) {
//your error code
console.log(err);
}
});
Many thanks
Basically what you need to do is to call node.js' API from your C# test code in a same way you call it using jQuery. There are several ways to do it:
Use HttpWebRequest class https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest%28v=vs.110%29.aspx
Use HttpClient class https://msdn.microsoft.com/en-us/library/system.net.http.httpclient%28v=vs.118%29.aspx It's more "RESTable" since it exposes methods to call HTTP methods like GET, PUT, POST and DELETE methods directly.
3rd party software http://restsharp.org/
Generally I recommend approach #2.
Here's the example source with all the rest of the code.
Another resource is the docs.
This code snippet should be enough to get you where you need.
using(var client = newHttpClient())
{
client.BaseAddress = newUri("http://localhost:55587/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(newMediaTypeWithQualityHeaderValue("application/json"));
//GET Method
HttpResponseMessage response = awaitclient.GetAsync("api/Department/1");
if (response.IsSuccessStatusCode)
{
Departmentdepartment = awaitresponse.Content.ReadAsAsync < Department > ();
Console.WriteLine("Id:{0}\tName:{1}", department.DepartmentId, department.DepartmentName);
Console.WriteLine("No of Employee in Department: {0}", department.Employees.Count);
}
else
{
Console.WriteLine("Internal server Error");
}
}

Check logged user with normal and ajax request

I use interceptor to check if a user is logged in every controller call like this :
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) {
if(request.getSession().getAttribute("user") == null) {
response.sendRedirect("redirect:/login?next="+
URLEncoder.encode(
request.getRequestURL().toString() + "" +
(request.getQueryString() != null ? "?" + request.getQueryString() : "")
,"utf-8");
return false;
}
return true;
}
It work fine for normal request but for ajax request i can't make a response.sendRedirect(..).
How to know if it's a ajax or normal request ?
How can i do it like if i got a ajax error ?
$.ajax({
.....
success : function(data) { ...... },
error : function(){
alert("login error"); // or
document.location = '/path/login' // or something else
}
});
There a other way to handle it rather than using interceptor ?
1. How to know if it's a ajax or normal request ?
You can check inside your interceptor for the existence of the X-Requested-With header. This header is always added to the ajax request by the jQuery library (to my knowing almost all major js libraries add it as well) with the purpose of preventing the Cross-Site request forgery. To figure out if the request is ajax, you can write your preHandle method like
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) {
String requestedWith = request.getHeader("X-Requested-With");
Boolean isAjax = requestedWith != null ? "XMLHttpRequest".equals(requestedWith) : false;
...
}
2. How can i do it like if i got a ajax error ?
As you've already noticed, ajax request don't recognize server side redirects, as the intention of the server side redirects is to be transparent to the client. In the case of an ajax request, don't do redirect rather set some status code to the response e.g. response.setStatus(respCode) or add a custom header e.g. response.setHeader("Location", "/path/login"), and read it through in the jQuery's complete method which is a callback that follows after either success or error, e.g.
$.ajax({
//...
complete: function(xhr, textStatus) {
console.log(xhr.status);
console.log(xhr.getResponseHeader('Location'));
// do something e.g. redirect
}
});
3. There a other way to handle it rather than using interceptor ?
Definitely. Checkout Spring Security. Its a framework, and adds a bit to the learning curve, but its well worth it. It will add much more than a custom solution, e.g. you'll get authorization mechanism on top of the authentication. When your application matures, you'll notice that the straigthforward implementation that you're on to now, has quite a few security flaws that are not hard to exploit e.g. session fixation, where spring security can easily protect you. There's plenty of examples online, and you'll get better support here on the SO in comparison to any custom solution. You can unit test it, an asset I personally value very much
You could simply:
Refuse ajax requests before the user is properly logged in
once the user logs in, set a security token in the session or somewhere
pass that token in the ajax request and use that token to validate on the server side prehandle
in your case you would check the existence of the token before running into the code
Also, the preHandle does not have to apply to every routes, you could also have different routes each with different authorisation, prehandle, code.

jsonp cross domain only working in IE

EDIT: At first I thought it wasn't working cross domain at all, now I realize it only works in IE
I'm using jQuery to call a web service (ASP.NET .axmx), and trying to us jsonp so that I can call it across different sites. Right now it is working ONLY in IE, but not in Firefox, Chrome, Safari. Also, in IE, a dialog pops up warning "This page is accessing information that is not under its control..."
Any ideas?
Here is the code:
$.ajax({
type: "POST",
url: "http://test/TestService.asmx/HelloWorld?jsonp=?",
dataType: "jsonp",
success: function(data) {
alert(data.prop1);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status + " " + textStatus + " " + errorThrown);
}
});
And the server code is:
[ScriptService]
public class TestService : System.Web.Services.WebService{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void HelloWorld() {
string jsoncallback = HttpContext.Current.Request["jsonp"];
var response = string.Format("{0}({1});", jsoncallback, #"{'prop1' : '" + DateTime.Now.ToString() + "'}");
HttpContext.Current.Response.Write(response);
}
}
Glad it's working now.
You're trying to send the parameter, "jsonp" -- that you need to pass for the "padding" part of the json -- as a GET parameter, i.e. in the URL string. Which is the right thing to do.
But because you've specified POST, that's not happening. Effectively, because you're specifying POST, the server is expecting all the parameters to be in the POSTed data, not in GET variables, so it's not checking the URL to retrieve the parameter.
I think it's possible that jQuery is being quite forgiving/smart about how it's doing the JSON evaluation, and therefore still working in IE, because (a) if the server doesn't read the "jsonp" variable, I think it'll send back "({'prop1' : '<today's date>'})", which is still evaluate-able as JSON, and (b) IE doesn't have the same restrictions on cross-site scripting ("same origin" policy) as the other browsers. But I'd need to debug it to be sure.
I'd suggest using FireBug in Firefox to debug what's going on with this sort of request in the future, but the main take-away is that if you're sending parameters as part of the URL, use GET, not POST.
Cheers,
Matt
Unless you specify the jsonp and/or the jsonpCallback option, jQuery auto-generates the function name for you, and adds a query param like callback=jsonp1272468155143. Which means your application needs to output using that function name.
You can always set jsonpCallback to test, in which case your example would work.

Jquery Ajax call to webservice is failing

Can anyone help? I have an issue with calling a asp.net webservice from jquery.. actually i think it maybe jquery ... as i have a break point and it doesn't arrive in the webservice..
Here is my jquery, the webservice method accepts 2 parameters...
So i setup a simple test to pass in 7 and 7 .. i tried replacing with the word "test" also and it doesn't work..
Basically lands in the error function which displays "sorry error happens" but the err is undefined.
jQuery.ajax({
type: 'POST'
, url: 'CallService.asmx/TempCanMakeCall'
, contentType: 'application/json; charset=utf-8'
, dataType: "json"
, data: "{'reservationNum':'7','completedReservationNum':'7'}"
, success: function(data, status) {
alert(data);
}
, error: function(xmlHttpRequest, status, err) {
alert('Sorry! Error happens.' + err);
}
}
);
Here is the asp.net webservice
[WebMethod()]
public bool TempCanMakeCall(string reservationNum, string completedReservationNum )
{
return true;
}
xmlHttpRequest.responseText has always been my goto when dealing with jQuery AJAX errors.
Try making your ASP.NET function static:
[WebMethod()]
public static bool TempCanMakeCall(string reservationNum, string completedReservationNum )
{
return true;
}
Also note that the returned JSON value is encapsulated in an object named 'd' (ASP.NET specific.) To display your return value upon success, you would need to do this:
success: function(data, status) {
alert(data.d);
}
The jquery ajax call looks fine. I think you need to make sure that the path to "CallService.asmx" is correct. The way it is now, I will only work if the file making the jQuery call is in the same virtual directory as the ASMX.
In your error callback function, you could check 'xmlHttpRequest.status' to get the http code returned from the server. This may give you another clue. If ichiban above is correct, it should be a 404.
You can check the xmlHttpRequest.responseText property. The response text is very probably an html document returned by the server that contains the reason for the error.
If you are using Visual Studio, you can also enable script debugging in Internet Explorer and put the following keyword in your error function: debugger. The browser sees this as a breakpoint and will invoke a debugger (which should be Visual Studio). Now you can check the entire contents of the xmlHttpRequest instance.
For clarity, your error function will then look like this:
function(xmlHttpRequest, status, err)
{
debugger;
...rest of your function...
}

JQuery AJAX Web Service call on SSL WebServer

I am making a POST to a webservice that is local to the webserver. Everything works great until I host the site at my SSL enabled webserver. The webservice path is relative, meaning, I am making no reference to the protocol. eg. /webservices/method.asmx
The POST results in a runtime error. Has anyone seen this before?
$.ajax({
type: "POST",
url: theURL + "/" + method,
data: body,
success: function (msg) {
alert("Data Saved: " + msg);
},
error: function (msg) {
alert("Broken: " + theURL + "/" + method + msg.responseText);
}
});
What happens if you specify an absolute url, including the protocol https:// piece... I usually put a javascript variable in my masterpages/template for "baseURL" for the prot://host:port/apppath/ reference... where port is only included if not the default. Haven't, iirc, seen such an issue.
Because this project is done in .NET 2.0.. the web method seems to handle the input data differantly. I was able to get around this by just construction a query sting and passing it rather than a JSON object.

Resources