-1

I have a login page and a welcome page. I have saved user details in my database.

It is working fine but problem is that user can go to the welcome page without login by changing the url of the webpage. How to set that without login user can not go to welcome page.

Here is my login page code-

Login.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;

public partial class Login : System.Web.UI.Page
{
    string con_string = ConfigurationManager.ConnectionStrings["testAzharConnectionString"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click1(object sender, EventArgs e)
    {

        SqlConnection con = new SqlConnection(con_string);
        string query = ("select count(*) from UserProfile where UserId ='" + txtUserId.Text + "' and Password='" + txtPassword.Text + "'");
        SqlCommand cmd = new SqlCommand(query, con);
        cmd.Connection = con;
        con.Open();
        int u = Convert.ToInt32(cmd.ExecuteScalar());
        con.Close();
        Captcha1.ValidateCaptcha(txtCaptcha.Text.Trim());
        if (u > 0 && Captcha1.UserValidated)
        {
            Response.Cookies["txtUserName"].Value = txtUserId.Text;
            Response.Redirect("Main.aspx");
        }
        else if (u == 0)
        {
            lblCaptcha.Text = "Unauthorized User";
            txtCaptcha.Text = "";
            txtUserId.Text = "";
            txtPassword.Text = "";
        }
        else
        {
            lblCaptcha.ForeColor = System.Drawing.Color.Red;
            lblCaptcha.Text = "You have Entered InValid Captcha Characters please Enter again";
            txtCaptcha.Text = "";
        }
    }
}

Login.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>
<%@ Register Assembly="MSCaptcha" Namespace="MSCaptcha" TagPrefix="rsv" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Login</title>
    <link rel="Stylesheet" href="StyleSheet.css" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <h1>Expense Management</h1>
    <h3>Please Login to manage Company Expenses.</h3>
    <table align="center" border="2" width="300">
        <tr>
            <td>User Id:</td>
            <td><asp:TextBox ID="txtUserId" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td>Password</td>
            <td><asp:TextBox ID="txtPassword" TextMode="Password" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td colspan="2">
                <rsv:CaptchaControl ID="Captcha1" runat="server" CaptchaLength="5"
                CaptchaHeight="60" CaptchaMinTimeout="5" CaptchaMaxTimeout="200"
                ForeColor="#00FFCC" BackColor="White" CaptchaChars="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
                FontColor="Red" Width="177px"/>
            </td>
        </tr>
        <tr>
            <td>Enter Captcha:</td>
            <td><asp:TextBox ID="txtCaptcha" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td><asp:Button ID="Button1" runat="server" Text="Login" onclick="Button1_Click1" /></td>
            <td><asp:Label ID="lblCaptcha" runat="Server" ForeColor="Red"></asp:Label></td>
        </tr>
        <tr>
            <td>
            <asp:HyperLink ID="linkForgetPassword" runat="server" ForeColor="Red" NavigateUrl="~/ForgetPassword.aspx">Forget Password ?</asp:HyperLink></td>
        </tr>
    </table>
    </form>
</body>
</html>

Please tell me how to set security on my login page.

Azhar Shahid
  • 151
  • 1
  • 4
  • 23
  • Setting the Session/Cookie when the user log into the system. Now fetch and check on the page if the Session/cookie is set or not. If its there than allow the user to view the page else redirect to login page. Done. Also don't forget to destroy the Session/Cookie when user logs out – Krunal Patil Jun 16 '14 at 05:06
  • @krunalPatil- can you please share some piece of code how to do this. – Azhar Shahid Jun 16 '14 at 05:08
  • You should parameterize your query. It is an sql injection waiting to happen. – scheien Jun 16 '14 at 05:10
  • the first security issue on your code is you are passing the essential info(username and pass) through your query without considering the SQL Injection attack. – Ali Jun 16 '14 at 05:10
  • @alishahrokhi.. ok, i will change it. – Azhar Shahid Jun 16 '14 at 05:11
  • @AzharShahid i have put a solution down there, and it also cover your question in regards to having multiple pages to check your user authentication – Ali Jun 16 '14 at 05:58

3 Answers3

3

here is a way to do your own login page

(you may need to change some codes in the following methods but it gives you an idea of how you could get this done without asp.net login control)

1.use web.config to set a form authentication, something like this:

 <authentication mode="Forms">
    <forms name="MYCOOKIE" loginUrl="Login.aspx" protection="All" 
         path="/" timeout="30">
      <credentials passwordFormat="MD5" />
    </forms>
  </authentication>

2.then set authenticaeRequest method to the Global.asax.cs like this:

    void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.User != null)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (HttpContext.Current.User.Identity is FormsIdentity)
                {
                    FormsIdentity formID =  
                         (FormsIdentity)HttpContext.Current.User.Identity;
                    FormsAuthenticationTicket ticket = formID.Ticket;

                    //get stored user data, in this case "user role"
                    string[] roles = new string[1] { ticket.UserData };
                    HttpContext.Current.User = new GenericPrincipal(formID, roles);
                }
            }
        }
    }

3.you need a class to set your cookie there use this one;

    public class CookieMaker
    {

    public CookieMaker()
    {

    }

    public HttpCookie CreateCookie(bool remembered, string user, string role)
    {
        DateTime dtExpire;
        bool persistent = false;

        if (remembered)
        {
            dtExpire = DateTime.Now.AddDays(14);
            persistent = true;
        }
        else
        {
            dtExpire = DateTime.Now.AddMinutes(30);
        }

        FormsAuthenticationTicket frmTicket =
            new FormsAuthenticationTicket(1,
                                        user,
                                        DateTime.Now,
                                        dtExpire,
                                        persistent,
                                        role,
                                        FormsAuthentication.FormsCookiePath);

        //encrypt the created ticket.
        string encryptTicket = FormsAuthentication.Encrypt(frmTicket);

        //create a new cookie using encripted ticket
        HttpCookie cookie = new HttpCookie(
                   FormsAuthentication.FormsCookieName, encryptTicket);

        //set date for cookie expiration if check-box has checked.
        if (frmTicket.IsPersistent)
            cookie.Expires = frmTicket.Expiration;

        return cookie;
    }
 }

4.in your login click button check your username and password , and set a role to that particular user like below:

protected void BtnLogin_Click(object sender, EventArgs e)
{
     try
        {
            string returnURL;
            HttpCookie mycookie;

            //set a role to the user if it's authenticated
            string role = GetRole(txtUserId.Text, txtPassword.Text); 
            if (role != string.Empty)
            {
                CookieMaker cookie = new CookieMaker();
                mycookie = cookie.CreateCookie(chkRemember.Checked, 
                                               txtUserId.Text, role);
            }

            if (cookie != null)
            {
                Response.Cookies.Add(cookie);
                Response.Redirect("Main.aspx");
            }
            else
                lblError.Text = "Invalid username or password.";
        }
        catch (Exception ex) { lblError.Text = ex.Message; }
}

    public string GetRole(string userID, string pass)
    {
        string role = string.Empty;

            sqlCmd.Connection = sqlCnn;
            sqlCnn.Open();

            sqlCmd.CommandText = @"SELECT COUNT([UserId]) from UserProfile 
                                          WHERE [UserId] = @username AND 
                                               [Password] = @password";
            sqlCmd.Parameters.AddWithValue("@username", userID);
            sqlCmd.Parameters.AddWithValue("@password", pass);

            if (Convert.ToInt32(sqlCmd.ExecuteScalar()) > 0)
                role = "Member";

            return role;
    }

Now you could set a base page class to check the rest of the pages before page load:

public class MemberPageBase : System.Web.UI.Page
{

    protected void Page_Init(object sender, EventArgs e)
    {
        if (!Context.User.Identity.IsAuthenticated)
        {
            this.RedirectToLogin();
        }
    }

    protected void RedirectToLogin()
    {
        Response.Redirect("~/Login.aspx");
    }
}

}

and the rest of the pages just inherits the code above like below:

public partial class Page1 : MemberPageBase 
{
    //....
}

so every time users trying to put the url straight away the page will redirect them to the login page if they are not authenticated.

Ali
  • 2,574
  • 1
  • 17
  • 24
2

It sounds like you don't have Membership or Roles configured. You should go through the tutorials on the ASP.NET site: Security Tutorials.

Dave4125
  • 31
  • 1
1

C# Code : (Setting the Session)

 protected void BtnLogin_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(con_string);
        string query = ("select count(*) from UserProfile where UserId ='" + txtUserId.Text + "' and Password='" + txtPassword.Text + "'");
        SqlCommand cmd = new SqlCommand(query, con);
        cmd.Connection = con;
        con.Open();
        int u = Convert.ToInt32(cmd.ExecuteScalar());
        con.Close();
        Captcha1.ValidateCaptcha(txtCaptcha.Text.Trim());
        if (u > 0 && Captcha1.UserValidated)
        {
            // Adding Session to your page
            Session["user"] = txtUserId.Text;

            Response.Cookies["txtUserName"].Value = txtUserId.Text;
            Response.Redirect("Main.aspx");
        }
        else if (u == 0)
        {
            lblCaptcha.Text = "Unauthorized User";
            txtCaptcha.Text = "";
            txtUserId.Text = "";
            txtPassword.Text = "";
        }
        else
        {
            lblCaptcha.ForeColor = System.Drawing.Color.Red;
            lblCaptcha.Text = "You have Entered InValid Captcha Characters please Enter again";
            txtCaptcha.Text = "";
        }

    }

on the page you want restricted access, check before loading the page :

protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            if (Session["user"] != null)
            {
                // Checking this session on the page, on the page load event.
                if (Session["user"] != null)
                {
                    Response.Redirect("Home1.aspx");
                }
            }
            else
            {
                Response.Redirect("Login.aspx");
            }
        }
    }

Last of all, Don't forget to destroy the session on logout or in Global file. Also use hashing to secure your password and comparing them.

Krunal Patil
  • 3,666
  • 5
  • 22
  • 28