63

Been stuck with this for hours

{"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}

I'm trying to call this WebMethod in my ASP.Net Webform

[WebMethod]
public static string GetClients(string searchTerm, int pageIndex)
{
    string query = "[GetClients_Pager]";
    SqlCommand cmd = new SqlCommand(query);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@SearchTerm", searchTerm);
    cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
    cmd.Parameters.AddWithValue("@PageSize", PageSize);
    cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
    return GetData(cmd, pageIndex).GetXml();
}

From this jquery.ajax

function GetClients(pageIndex) {
    $.ajax({
        type: "POST",
        url: "ConsultaPedidos.aspx/GetClients",
        data: '{searchTerm: "' + SearchTerm() + '", pageIndex: ' + pageIndex + '}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function (response) {
            alert(response.d);
            },
            error: function (response) {
                alert(response.d);
            }
    });
}

But I always get this error:

POST http://localhost:64365/ConsultaPedidos.aspx/GetClients 401 (Unauthorized)

Weird thing is that this used to work until I start authenticating users

<system.web>
...
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" defaultUrl="/Dashboard" />
    </authentication>
    <authorization>
      <deny users="?" />
    </authorization>
...
</system.web>

Any ideas?

Daniel Cardenas
  • 2,826
  • 2
  • 19
  • 17

13 Answers13

195

Problem solved

This was driving me crazy.

Inside ~/App_Start/RouteConfig.cs change:

settings.AutoRedirectMode = RedirectMode.Permanent;

To:

settings.AutoRedirectMode = RedirectMode.Off;

(Or just comment the line)

Also if friendly URLs are enabled you need to change

url: "ConsultaPedidos.aspx/GetClients",

To:

url: '<%= ResolveUrl("ConsultaPedidos.aspx/GetClients") %>',

Hope this help somebody else

Community
  • 1
  • 1
Daniel Cardenas
  • 2,826
  • 2
  • 19
  • 17
  • 7
    I wanted to thank you for this answer, this solved the issue for me. I've seen people asking about this problem on several sites, but you were the only one that offered a solution. – cost May 16 '14 at 06:06
  • 8
    I just have the same issue! but I use Asp.net web project, i have no ~/App_Start/RouteConfig.cs.... how can I solve it.. – Kun-Yao Wang Dec 29 '16 at 09:17
  • How to fix this error in asp.net 3.5 web form project ? It doesn't have any routeconfig.cs file. – shrekDeep Jul 25 '18 at 09:03
  • I've found so many guides that recommend changing settings like `web.config`, etc, but this is the only solution that worked. It's quite surprising that this functionality doesn't work out of the box. – tresf Oct 31 '19 at 21:01
  • Using an out of the box C# ASP.NET Webforms project, friendly URLs were enabled. Note that changing AutoRedirectMode to AutoRedirectMode.Off was all I needed to do. Much thanks. – IdusOrtus Feb 04 '20 at 19:07
21

Inside ~/App_Start/RouteConfig.cs change

settings.AutoRedirectMode = RedirectMode.Permanent;

to

settings.AutoRedirectMode = RedirectMode.Off;
Sabyasachi Mishra
  • 1,677
  • 2
  • 31
  • 49
user3913452
  • 353
  • 3
  • 8
6

401 Unauthorised means that:

  • User authentication hasn't been provided or
  • It was provided but failed authentication tests

This corroborates with what you've said about adding authentication, it's clearly covering this method too.

Therefore do you want access to this method to be public or not?

Public:

  • You need to remove authentication from this method.

To allow access to public resources (such as this webmethod) you simply place this in the config file in the same directory:

 <authorization>
        <allow users="*" /> 
 </authorization>

if you put above tag then it will give access right to all kind of users to all resources. so instead of that you can add below tag to give authorization to the web service

<location path="YourWebServiceName.asmx">
<system.web>
  <authorization>
    <allow users="*"/>
  </authorization>
</system.web>

Private:

  • You need to ensure authentication is being sent across the line (using Fiddler to check for the cookie), and ensure it's is passing asp.net authentication.
Community
  • 1
  • 1
m.edmondson
  • 30,382
  • 27
  • 123
  • 206
  • Thanks for the answer. I've already tried `` but I get the same response, also when checking the cookie on Fiddler it says this: `This response did not set any cookies.` – Daniel Cardenas Apr 12 '14 at 17:40
  • This looks like the culprit, without any cookies any **authentication will fail** - so figure out how to remove authentication from the method. – m.edmondson Apr 12 '14 at 17:43
5

You have to comment out only in ~/App_Start/RouteConfig.cs

  // settings.AutoRedirectMode = RedirectMode.Permanent;

             (Or do this)

    settings.AutoRedirectMode = RedirectMode.Off;

There is nothing to do with Authentication in Web.config file.

Md Shahriar
  • 2,072
  • 22
  • 11
  • In my case I had friendly URL settings in routing config which by default set with AutoRedirectMode to permanent, service method hitting after turning it off. Thank you. – Ravi Shankar Dec 03 '19 at 01:21
3

I found this question trying to solve the same problem, the way I solved is not seen here so I post to someone stuck in the same bottleneck:

Try in your method use the EnableSession = true in your WebMethod attribute

like

[WebMethod(EnableSession = true)]
public static string MyMethod()
{
    return "no me rindo hdp";
}

with this is solved my 401 error. Hope be helpful.

RokumDev
  • 367
  • 4
  • 13
3

In my case, I was adding the WebMethod to a control on the form. It needs to be added to the page itself.

Jeff Davis
  • 4,736
  • 4
  • 38
  • 44
2

Not an expert but have you tried by putting <allow users="*"/> in the config file? Your request should be using a GET method and not a POST (used to create).

EDIT: It seems that you are using a SOAP method, which can't be called from clientside, you should use a RESFUL service.

bobthedeveloper
  • 3,733
  • 2
  • 15
  • 31
2

For me, I had an invalid "data:" parameter in my JQuery Ajax call. But rather than either .NET or JQuery complaining about the the parameter values, I was (misleadingly in my opinion) getting the 401 Unauthorized error.

Der Wolf
  • 1,171
  • 9
  • 11
1

I faced the same problem and firstly tried the solution which is available and it does work. However I realised if I create a new web-service and add the relevent code in the App_Code folder of the web-service file then I don't get any errors.

Izzy
  • 6,740
  • 7
  • 40
  • 84
  • can you be a bit more specific? I too tried these things but the error just changed, it enters the Error event with: Status: error Error: Internal Server Error, no details. thanks – Bogdan T Stancu Aug 07 '15 at 14:33
  • Never mind, I got it working. It was expecting JSON so I had to to JSON.stringify(..datavalue), it works now. – Bogdan T Stancu Aug 07 '15 at 14:42
1

I know you got your answer accepted. It actually happens while creating a Web Form application and not changing the Authentication to No Authentication.

The default authentication we see as Authentication: Individual User Account

The error will not come if we change to Authentication: No Authentication

Sabyasachi Mishra
  • 1,677
  • 2
  • 31
  • 49
  • would like to point out that this does happen with 2017 VS (i use community ed) and web forms app, even with 'No Authentication'. I had to modify the routeconfig .cs as detailed above. – zingh May 17 '18 at 03:16
1

My site was using ASP.NET forms authentication and I worked out by trial and error that I could only get it work if I called a web method with on an .asmx page and with contentType: "application/x-www-form-urlencoded" and dataType: "xml"

Matthew Lock
  • 13,144
  • 12
  • 92
  • 130
1

In my case the problem was in URL that calls Ajax.asmx this URL was not correct according to a webserver setup, e.g. "/qa/Handlers/AjaxLib.asmx/" worked for me instead of "/Handlers/AjaxLib.asmx/" (works fine on PROD servers in my particular situation):

  $.ajax({
  url: '/qa/Handlers/AjaxLib.asmx/' + action,
  type: "POST",
  async: false,
  data: data,
  contentType: "application/json; charset=utf-8",
  success: function () {

My AJAX was then called out of scope of my IIS virtual application directory "qa", hence Authorization error occured ({"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}).

Roshna Omer
  • 687
  • 1
  • 11
  • 20
Honza P.
  • 1,165
  • 1
  • 11
  • 12
1

To allow this Web Service to be called from script, using ASP.NET AJAX. Add the following attribute to the class

[System.Web.Script.Services.ScriptService]

I faced similar issue and the adding this attribute resolved it.

Bilal Alam
  • 874
  • 10
  • 26