Implement Form based Authentication with Web Service (ASMX) using C# in ASP.Net

Amit
 
on May 28, 2020 03:41 AM
1570 Views

How to create a web service with form based authentication.

As web service doesn't have UI, how can we implement form based authentication in asp.net web service.

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on May 28, 2020 03:42 AM

I will get back to you soon.

dharmendr
 
on May 28, 2020 05:17 AM

Hi Amit,

Using the article i have created the example.

ASP.Net Login RedirectUrl: Redirect to requested page after Login in ASP.Net using C# and VB.Net

Refer below code.

HTML

Login

<asp:Login ID="Login1" runat="server" OnAuthenticate="ValidateUser">
    </asp:Login>

Home

Welcome
<asp:LoginName ID="LoginName1" runat="server" Font-Bold="true" />
<br />
<br />
<asp:Label ID="lblLastLoginDate" runat="server" />
<asp:LoginStatus ID="LoginStatus1" runat="server" />

Code

WebService

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;

namespace User_Login
{
    /// <summary>
    /// Summary description for WebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class WebService : System.Web.Services.WebService
    {
        [WebMethod]
        public string ValidateUser(string userName, string password, bool rememberMe)
        {
            int userId = 0;
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("Validate_User"))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Username", userName);
                    cmd.Parameters.AddWithValue("@Password", password);
                    cmd.Connection = con;
                    con.Open();
                    userId = Convert.ToInt32(cmd.ExecuteScalar());
                    con.Close();
                }
                string message = "";
                switch (userId)
                {
                    case -1:
                        message = "-1";
                        break;
                    case -2:
                        message = "-2";
                        break;
                    default:
                        message = "1";
                        break;
                }

                return message;
            }
        }

        [WebMethod]
        public bool IsAuthenticated()
        {
            if (Context.User.Identity.IsAuthenticated)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

Login

LoginReference.WebServiceSoapClient client;
protected void Page_Load(object sender, EventArgs e)
{
    client = new LoginReference.WebServiceSoapClient();
    if (client.IsAuthenticated())
    {
        Response.Redirect(FormsAuthentication.DefaultUrl);
    }
}
protected void ValidateUser(object sender, EventArgs e)
{
    string message = client.ValidateUser(Login1.UserName, Login1.Password, Login1.RememberMeSet);
    if (message == "-1")
    {
        Login1.FailureText = "Username and/or password is incorrect.";
    }
    if (message == "-2")
    {
        Login1.FailureText = "Account has not been activated.";
    }
    if (message == "1")
    {
        if (!string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
        {
            FormsAuthentication.SetAuthCookie(Login1.UserName, Login1.RememberMeSet);
            Response.Redirect(Request.QueryString["ReturnUrl"]);
        }
        else
        {
            FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet);
        }
    }
}

Home

LoginReference.WebServiceSoapClient client;
protected void Page_Load(object sender, EventArgs e)
{
    client = new LoginReference.WebServiceSoapClient();
    if (client.IsAuthenticated())
    {
        FormsAuthentication.RedirectToLoginPage();
    }
}