How to use authentication on a custom login.aspx webform

Donald Symmons 2,856 Reputation points
2023-01-11T16:52:20.1933333+00:00

Please forum,

I know I asked lots of questions about this issue, but I need you guys to help me out with my own code here.

Recently, I read about authenticating users based on their roles. The webforms used were default webforms with its controls, but I will love to use my own custom created webform and controls.

Is it possible to use windows/forms authentication on a custom login page?

I created a login page and I will love to use authentication o the page and redirect base on Roles.

Here is my database tables schema

Users

IdemailPass_wordNameLastLoginIsAcitveRoleId1admin@admin.comxxxxxxxAdministrator1/11/2023 1:07:28 PM012client@client.comxxxxxxxClient1/11/2023 1:07:28 PM023clientuser@use.comxxxxxxClientUser1/11/2023 1:07:28 PM03Roles Table

RoleIdRoleName1Administrator2Client3ClientUser*Administrator means user has all rights

*Client means user has limited rights to some pages but more rights than Clientuser.

I successfully created an Administrator record inside the Users table. I will like to know how I can add an authentication to the login and other webpages (using my code below), and redirect admin to admin page on successful login; also redirect other users to other webpages meant for them.

My code is presented below, Please what can I add to the code for the authentication to take place?

HTML

<!-- Login starts-->
        <div class="row" style="width: 100%; margin: 0 auto;">
            <div class="col-sm-5" style="margin: 0 auto;">
                <div class="container-fluid">
                    <br />
                    <h2 class="form-signin-heading" style="color: #355171; text-align: center; font-weight: 500; font-size: 13pt; margin-top: -4px;">LOGIN</h2>
                    <div id="dvMessage" runat="server" visible="false" class="alert alert-danger" style="margin-bottom: 1%;">
                        <strong><i class="fad fa-exclamation-square" aria-hidden="true" style="margin: 0 7px; font-size: 13pt;"></i>&nbsp;</strong><asp:Label ID="lblMessage" runat="server" />
                    </div>
                    <label for="txtUsername" style="font-weight: 500;">Email</label>
                    <asp:TextBox ID="txtUsername" runat="server" CssClass="form-control" Font-Size="11pt" placeholder="Email Address" Width="100%" />
                    <br />
                    <label for="txtPassword" style="font-weight: 500;">Password</label>
                    <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" CssClass="form-control" Font-Size="11pt" placeholder="Password" />
                    <a href="#" style="color: #075481; float: right; text-decoration: none; font-size: 10pt;">Forgotten Password?</a>
                    <br />
                    <br />
                    <asp:Button ID="Button1" runat="server" CssClass="btn btn-primary" BackColor="#32657c" Text="Login" OnClick="ValidateUser" />
                    <br />
                    <br />
                </div>
                <br />
            </div>
        </div>
        <!--Login ends-->

Login Code

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Text;
using System.Security.Cryptography;
using System.IO;

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            //using the Identity IsAuthenticated method on login page load event to redirect user if not authenticated
            if (this.Page.User.Identity.IsAuthenticated)
            {
                FormsAuthentication.SignOut();
                Response.Redirect("~/Login.aspx");
            }
        }
    }

    protected void ValidateUser(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(txtUsername.Text) & !string.IsNullOrEmpty(txtPassword.Text))
        {
            SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\QuirverData.mdf;Integrated Security = True");
            string check = "SELECT Uid FROM Users WHERE pass = @pass COLLATE SQL_Latin1_General_CP1_CS_AS AND email = @email AND pass = @pass";
            SqlCommand com = new SqlCommand(check, con);
            con.Open();
            com.Parameters.AddWithValue("@email", txtUsername.Text.Trim());
            com.Parameters.AddWithValue("@pass", Encrypt(txtPassword.Text.Trim()));
            string Uid = Convert.ToString(com.ExecuteScalar());
            con.Close();

            //checks to see if logi details are correct
            if (!string.IsNullOrEmpty(Uid))
            {
                string users = "";
                //checks to see if account has been activated
                using (SqlCommand cmd = new SqlCommand("SELECT Uid FROM UserActivation WHERE Uid = @Uid"))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@Uid", Uid);
                    cmd.Connection = con;
                    con.Open();
                    users = Convert.ToString(cmd.ExecuteScalar());
                    con.Close();
                }
                if (string.IsNullOrEmpty(users))
                {
                    int user = 0;
                    using (SqlCommand cmd = new SqlCommand("SELECT Uid FROM Users WHERE pass = @pass COLLATE SQL_Latin1_General_CP1_CS_AS AND email = @email AND pass = @pass"))
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.AddWithValue("@email", txtUsername.Text.Trim());
                        cmd.Parameters.AddWithValue("@pass", Encrypt(txtPassword.Text.Trim()));
                        cmd.Connection = con;
                        con.Open();
                        user = Convert.ToInt32(cmd.ExecuteScalar());
                        con.Close();
                    }
                    if (user > 0)
                    {
                        //if account has been activated, it select lastlogin date and IsActive coulmns and updates them on login
                        Session["user"] = user;
                        con.Open();
                        string query = "SELECT LastLogin, IsActive from Users WHERE Uid = @Uid";
                        using (SqlCommand cmd = new SqlCommand(query, con))
                        {
                            cmd.Parameters.AddWithValue("@Uid", Session["user"]);
                            Session["LastLogin"] = Convert.ToDateTime(cmd.ExecuteScalar());
                        }
                        string UpdateLog = @"UPDATE Users SET LastLogin=@dateandtime, IsActive=@IsActive WHERE Uid = @Uid";
                        using (SqlCommand cmd = new SqlCommand(UpdateLog, con))
                        {
                            cmd.Parameters.AddWithValue("@dateandtime", DateTime.UtcNow);
                            cmd.Parameters.AddWithValue("@IsActive", "1");
                            cmd.Parameters.AddWithValue("@Uid", Session["user"]);
                            cmd.ExecuteNonQuery();
                        }
                        con.Close();
                    }
                    Session["user"] = user;
                    Response.Redirect("Home.aspx?Id=" + user);
                }
                else
                {
                    dvMessage.Visible = true;
                    lblMessage.Visible = true;
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                    lblMessage.Text = "Account has not been activated";
                    txtPassword.Text = "";
                    txtPassword.Focus();
                }
            }
            else
            {
                dvMessage.Visible = true;
                lblMessage.Visible = true;
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text = "Invalid Login Details";
                txtPassword.Text = "";
                txtPassword.Focus();
            }
        }
        else
        {
            dvMessage.Visible = true;
            lblMessage.Visible = true;
            lblMessage.ForeColor = System.Drawing.Color.Red;
            lblMessage.Text = "All Fields are Required";
        }
    }

    private string Encrypt(string clearText)
    {
        //This encrypts the password
        string EncryptionKey = "MAKV2SPBNI99212";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);

        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
    }
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,287 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,302 questions
{count} votes

Accepted answer
  1. Lan Huang-MSFT 25,876 Reputation points Microsoft Vendor
    2023-01-12T03:16:11.9633333+00:00

    Hi @Donald Symmons,

    Is it possible to use windows/forms authentication on a custom login page?

    Yes, you can check the documentation for specific steps:

    Implement forms-based authentication in an ASP.NET application by using C#.NET

    1. Configure Authorization and Authentication settings in web.config
    2. A login page and execute logic to authenticate provided credential of windows user
    3. If provided credentials are authenticated in step 2, then generate an authentication token so that user should be able to navigate into the authorized pages of your application.

    Best regards,

    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful