{"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"} Error in web method using form authentication

Amin Jariwala 1 Reputation point
2022-10-08T08:33:27.64+00:00

Hi All,

I am using ASP.NET 4.8 Web form to build login functionality using form authentication. When user click on Sign in it will call method from my service.asmx file.

Service.asmx
[WebMethod(EnableSession = true)]
public string signin(string email, string password)
{
string output = string.Empty;
EmployeeBAL objEmployeeBAL = new EmployeeBAL();

        try  
        {  
            objEmployeeBAL.Email = email;  
            DataTable dtHasCustomer = objEmployeeBAL.GetEmployeePassword();  

            if (dtHasCustomer.Rows.Count > 0)  
            {  
                if (Utilities.VerifyHash(password, dtHasCustomer.Rows[0][0].ToString()))  
                {  
                    objEmployeeBAL.Password = dtHasCustomer.Rows[0][0].ToString();  

                    DataTable dtEmployee = objEmployeeBAL.EmployeeLogin();  

                    if (!dtEmployee.Columns[0].ColumnName.ToLower().Contains("error"))  
                    {  
                        if (dtEmployee.Rows.Count > 0)  
                        {  
                            if ((bool)dtEmployee.Rows[0]["IsActive"])  
                            {  
                                //create form auth cookie  
                                FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(  
                                    1,  
                                    dtEmployee.Rows[0]["Name"].ToString(),  
                                    DateTime.Now,  
                                    DateTime.Now.AddHours(1),  
                                    true,  
                                    dtEmployee.Rows[0]["Id"].ToString() + "," + dtEmployee.Rows[0]["RoleId"].ToString() + "," + email);  
                                string cookie = FormsAuthentication.Encrypt(tkt);  
                                HttpCookie httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookie);  
                                FormsAuthentication.RedirectFromLoginPage(dtEmployee.Rows[0]["Name"].ToString(), true);  
                                httpCookie.Expires = tkt.Expiration;  
                                httpCookie.Path = FormsAuthentication.FormsCookiePath;  
                                Context.Response.Cookies.Add(httpCookie);  

                                //create cookie to store user email  
                                HttpCookie emailCookie = new HttpCookie("Email");  
                                emailCookie.Value = email;  
                                emailCookie.Expires = DateTime.Now.AddDays(30);  
                                Context.Response.Cookies.Add(emailCookie);  

                                Context.Request.Cookies["Email"].Value = email;  
                            }  
                            else  
                            {  
                                output = "Your account has been <b>Disabled</b> temporarily.";  
                            }  
                        }  
                        else  
                        {  
                            output = "Invalid Email 0r Password";  
                        }  
                    }  
                    else  
                    {  
                        output = dtEmployee.Rows[0][0].ToString();  
                    }  
                }  
                else  
                {  
                    output = "Invalid Email 0r Password.";  
                }  
            }  
            else  
            {  
                output = "Invalid Email 0r Password.";  
            }  
        }  
        catch (Exception ex)  
        {  
            Global g = new Global();  
            g.HandleErrorLog(ex, ErrorLevel.Error);  
            output = ex.Message;  
        }  
          
        return (output == string.Empty) ? "success" : output;  
    }  

Web.config
<location path="Service.asmx/signin">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Service.asmx/signin" defaultUrl="~/default" protection="Encryption" name="cwfw"></forms>
</authentication>
<compilation debug="true" targetFramework="4.8" />
<httpRuntime targetFramework="4.8" requestValidationMode="2.0" maxRequestLength="52428800" maxQueryStringLength="80000" maxUrlLength="10000" executionTimeout="3600" />
<pages validateRequest="false" enableEventValidation="false">
<namespaces>
<add namespace="System.Web.Optimization" />
</namespaces>
<controls>
<add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
</controls>
</pages>
</system.web>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

When I try to login it is throwing below error:
{"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}

HTML:
<button type="button" id="signin" class="btn btn-primary">Sign in</button>

Calling webmethod by AJAX call:
$('#signin').click(function () {
$.ajax({
url: '<%= GlobalSettings.websiteurl + "/Service.asmx/signin" %>',
data: "{ 'email': '" + $('#txtEmail').val() + "',password: '" + $('#txtPassword').val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data != undefined && data.d != null) {
//alert(data.d);
if (data.d == "success") {
$('.login-msg').text('You are not loggedin.');
setTimeout(function () {
location.reload();
}, 2000);
}
else {
$('.login-msg').text(data.d);
//alert(data.d);
}
}
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
});

Please help me.
Thanks.

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,326 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. AgaveJoe 26,246 Reputation points
    2022-10-08T11:12:46.003+00:00

    Your design has a lot of issues and you did not supply all the relevant code.

    Clearly the catch is firing but the design overwrites the actual error. Remove the try...catch while debugging to get the actual error. Once the code is working as expected then add the try catch.

    Please use the Visual Studio debugger to single step through your code. Any of the method calls like objEmployeeBAL.GetEmployeePassword() could be throwing an exception too.

    First look at the Visual Studio Debugger

    The browser also has debugging tools; press F12. Rather than using alert to view variables write to the console.

    console.log("Hello World");  
    

    you can also single step JavaScript.

    0 comments No comments

  2. Amin Jariwala 1 Reputation point
    2022-10-08T11:21:01.283+00:00

    Code does not have any issue I debug it and it is returning success in string. Also after removing try catch still getting the same error.


  3. Amin Jariwala 1 Reputation point
    2022-10-09T07:20:29.937+00:00

    Thanks All for your help.

    Issue is resolved now.

    Solution: I have used Web API instead of Web Method and it is working fine with the same code.