Solved

Authentication Login via Access DB

Posted on 2008-06-16
34
211 Views
Last Modified: 2013-12-17
I have connected my login system with the access database using the hashing as my login system. I am doing this in Visual Studio .Net 2005 in c#. The only trouble I am having is the authentication part.

I would not like users to view my web pages without logging in. Also would like a time out session after 10 mins or something.

Can you please help me.

introlux
0
Comment
Question by:introlux
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 18
  • 16
34 Comments
 
LVL 1

Expert Comment

by:trenduin
ID: 21798496
You should be able to add the code below, in the Page_Load area of your pages.
        //set timeout
        int xMin = 10;
        Session.TimeOut = xMin;
 
        //see if authenticated
        if (User.Identity.IsAuthenticated == false)
        {
            Server.Transfer("login.aspx");
        }
        else if (User.IsInRole("Basic User") == false)
        {
            Server.Transfer("unauthorized.aspx");
        }

Open in new window

0
 
LVL 1

Expert Comment

by:trenduin
ID: 21798500
Oops. It's supposed to be Session.Timeout = xMin; Sorry old VB 6 habits. =o)
0
 

Author Comment

by:introlux
ID: 21801023
Right the code is accepted and does take user to the login page. After entering the correct login details i cannot redirect that user to the default page where I inserted the code you gave me on the page load.
0
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 

Author Comment

by:introlux
ID: 21801028
Thats the Login.aspx code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<%@ Import Namespace="System.Data.OleDb" %>
<%@ Import Namespace="System.Web.Security" %>
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Password Hashing (CS)</title>
<script runat="server" language="C#">
    OleDbConnection objConn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\\ProCom.mdb");
OleDbCommand objCmd;
OleDbDataReader objDR;
 
bool CheckCredentials(string Username, string Password) {
	objConn.Open();
	OleDbCommand objCmd = new OleDbCommand("SELECT Salt, Pass FROM Users WHERE Username=@givenUsername", objConn);
	objCmd.Parameters.Add("@givenUsername", Username);
 
	objDR = objCmd.ExecuteReader();
	if (!objDR.Read()) {
		return false;
	} else {
		string strSalt = (string) objDR["Salt"];
		string strStoredPassword = (string) objDR["Pass"];
		string strGivenPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(strSalt + Password, "SHA1");
		return strStoredPassword == strGivenPassword;	
	}
}
 
void CheckCredentials_Click(Object s, EventArgs e) {
	if (CheckCredentials(txtUsername.Text, txtPassword.Text) == true) {
        lblCheck.Text = "You entered the right credentials!";
        Response.Redirect("Default.aspx");
	} else {
		lblCheck.Text = "You entered the wrong credentials!";
	}
}
</script>
</head>
<body>
 
<form id="FormLogin" runat="server">
    <strong>Project Commissioning System<br />
        <br />
        <br />
        Login:</strong><br /><br />
Username: <asp:TextBox id="txtUsername" runat="server" /><br />
Password: <asp:TextBox id="txtPassword" runat="server" TextMode="Password" /><br /><br />
<asp:Button id="btnCheck" runat="server" Text="Check Credentials" onClick="CheckCredentials_Click" /><br /><br />
<asp:Label id="lblCheck" runat="server" />
 
</form>
</body>
</html>

Open in new window

0
 

Author Comment

by:introlux
ID: 21804698
any joy??????????????
0
 
LVL 1

Expert Comment

by:trenduin
ID: 21804747
Sorry about that. You just need to add another line. I'm not sure about your roles, if you just have one then you can remove one part as well. Here's an updated version.
        //set timeout
        int xMin = 10;
        Session.TimeOut = xMin;
 
        //see if authenticated
        if (User.Identity.IsAuthenticated == false)
        {
            Server.Transfer("login.aspx");
        }
        //remove this if you don't care about roles
        else if (User.IsInRole("Basic User") == false)
        {
            Server.Transfer("unauthorized.aspx");
        }
        else if (User.Identity.IsAuthenticated == true)
        {
            Server.Transfer("my_secured_page.asp");
        }

Open in new window

0
 
LVL 1

Expert Comment

by:trenduin
ID: 21804763
Oh if you remove the line about roles then you can just use an else statement like this:
        //set timeout
        int xMin = 10;
        Session.TimeOut = xMin;
 
        //see if authenticated
        if (User.Identity.IsAuthenticated == false)
        {
            Server.Transfer("login.aspx");
        }
        else
        {
            Server.Transfer("my_secured_page.asp");
        }

Open in new window

0
 
LVL 1

Expert Comment

by:trenduin
ID: 21804795
Just so you know, most of this is based of the idea of using the login controls provided by visual studio with a custom data source. You can all about that by going here:

http://support.microsoft.com/kb/910440
0
 

Author Comment

by:introlux
ID: 21811487
I have gone through this, and this is showing how to setup everything from scratch. I already have a login and register system. All I want is an authentication setup. So when user tries to access a normal web page, it should not be working.

One thing I have noticed with asp.net c# that there are so many different ways in doing one particular process. There must be methods out there straight forward.

Thanks
0
 

Author Comment

by:introlux
ID: 21864066
????????
0
 
LVL 1

Expert Comment

by:trenduin
ID: 21880685
Ok, you would probably want to create a session variable that holds the username, or password, or the ID number for the user that is in the database. Then all you have to do is check for the value of the session variable on each secured page. If the variable doesn't exist, or is empty then redirect them to the login page, otherwise load the page.
void CheckCredentials_Click(Object s, EventArgs e) {
        if (CheckCredentials(txtUsername.Text, txtPassword.Text) == true) {
            Session("usrName") = txtUsername.Text;
 
        } else {
                lblCheck.Text = "You entered the wrong credentials!";
        }
}
 
//Add the following code in the load function of secure pages
        if (Session("usrName") == "")
        {
            Response.Redirect("login.aspx");
        }

Open in new window

0
 

Author Comment

by:introlux
ID: 21881661
Im getting the following error message:

Compiler Error Message: CS0118: 'System.Web.UI.Page.Session' is a 'property' but is used like a 'method'

Source Error:

 

Line 14:     protected void Page_Load(object sender, EventArgs e)
Line 15:     {
Line 16:         if (Session("usrName") == "")
Line 17:         {
Line 18:             Response.Redirect("login.aspx");
 
0
 

Author Comment

by:introlux
ID: 21881778
I think you require to use ["usrName"] instead of ("usrName")

But this compiles and runs, but it does not do anything...........

It still allows you to view other secured web pages even though I have inserted the above code in the page load behind the code.

any idea???
0
 

Author Comment

by:introlux
ID: 21885435
Any help???
0
 
LVL 1

Expert Comment

by:trenduin
ID: 21885809
I'm working on it.
0
 
LVL 1

Expert Comment

by:trenduin
ID: 21887269
try this instead
void CheckCredentials_Click(Object s, EventArgs e) {
        if (CheckCredentials(txtUsername.Text, txtPassword.Text) == true) {
            Session.Add("usrName") = txtUsername.Text;
 
        } else {
                lblCheck.Text = "You entered the wrong credentials!";
        }
}
 
//Add the following code in the load function of secure pages
        if (Session["usrName"] == null)
        {
            Response.Redirect("login.aspx");
        }

Open in new window

0
 

Author Comment

by:introlux
ID: 21897481
I am now recieving the following error message:

Compiler Error Message: CS1501: No overload for method 'Add' takes '1' arguments

Source Error:

 

Line 46:         if (CheckCredentials(txtUsername.Text, txtPassword.Text) == true)
Line 47:         {
Line 48:             Session.Add("usrName") = txtUsername.Text;
Line 49:             Response.Redirect("LogSess.aspx");
Line 50:         }
 
0
 
LVL 1

Accepted Solution

by:
trenduin earned 500 total points
ID: 21901082
wow it just hasn't been my day recently. I keep forgetting things. =o)

Session.Add("usrName",txtUsername.Text);
0
 

Author Comment

by:introlux
ID: 21905780
wicked!! top man!!

I have had this issue for like 2 weeks and you have been the only guy to find it out!!

Thanks so much!

introlux
0
 

Author Closing Comment

by:introlux
ID: 31467495
Top Answer!!
0
 
LVL 1

Expert Comment

by:trenduin
ID: 21905813
I'm making a custom role and membership provider that will support custom databases by allowing you to specify information in a config file. That way you can use the Asp.Net login controls which makes life a whole lot easier. =o) At any rate I had been fighting with similar issues for a while, it would've went faster if I was trying to do it from memory. =o)
0
 

Author Comment

by:introlux
ID: 21905868
When you get around making the custom role and membership provider. Will be interesting to have a look at this. Drop me an e-mail at introlux@hotmail.com

Thanks! and once again thanks for the help, really appreciate it.
0
 
LVL 1

Expert Comment

by:trenduin
ID: 21905877
no problem. What site are you working on? If you don't mind me asking.
0
 

Author Comment

by:introlux
ID: 21906054
Its a web site for internal use where users will be able to enter data, will be stored in access. Also save hard copy of data in a readable format like xml. Only problem which I am working on at the mo is trying to learn how I can format the xml data to display it in a report format rather than in a row.

Also I had problems using login control using asp.net on my personal web site. (www.proevolive.co.uk).

Since I introduced the login controls using asp.net, you cannot view the web site anymore. Contacted the host to see what the problem was, and they informed me to point my application to their DNS which I dont understand how to. So im planning to go into my code and edit it to have the same type of login controls like the one I have done using your help.
0
 
LVL 1

Expert Comment

by:trenduin
ID: 21906164
Glad I could help.
0
 

Author Comment

by:introlux
ID: 21906319
Last quick question, Have you managed to have a sign out button or some sort?? or remember me??

Just curious - if not then dont worry
0
 
LVL 1

Expert Comment

by:trenduin
ID: 21906380
Under a signout button code you just add the Session.Abandon() and redirect to a different page. You can use cookies to include a remember me option, then check for the cookie or the session item.
0
 

Author Comment

by:introlux
ID: 21906397
Do you have an example of the remember me using cookies
??
0
 
LVL 1

Expert Comment

by:trenduin
ID: 21908644
It would be something along these lines, but you would probably want to include an encrypted password, or just some kind of key instead of just a user name.
    protected void Page_Load(object sender, EventArgs e)
    {
        if(Request.Cookies["userName"]!=null)
        {
            Session.Add("userName",Request.Cookies["userName"].Value.ToString());
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (rememberMe.Checked)
        {
            HttpCookie myCookie = new HttpCookie("userName", "user");
            Response.Cookies.Add(myCookie);
        }
    }

Open in new window

0
 

Author Comment

by:introlux
ID: 21952134
Just wanted to ask, have you come with an solution in when user registers, the active check box in access (field) has to be ticked in order for user to login. Is there a method that this can be done, as I would not want anyone registering.

Thanks,

introlux
0
 
LVL 1

Expert Comment

by:trenduin
ID: 21952221
Check boxes in access should return boolean values of true or false you would just need to add a check for that value in your login code, along with username and password.
0
 

Author Comment

by:introlux
ID: 21952273
I have added the new field Active in the checkcredentials but i cant seem to know how i can code that into the btnLogin function.
bool CheckCredentials(string Username, string Password)
    {
        OleDbConnection objConn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("Data/ProCom.mdb"));
        OleDbCommand objCmd = new OleDbCommand("SELECT Salt, Pass FROM Users WHERE Username=@givenUsername", objConn);
        OleDbDataReader objDR;
 
        objConn.Open();
        objCmd.Parameters.Add("@givenUsername", Username);
 
        objDR = objCmd.ExecuteReader();
        if (!objDR.Read())
        {
            return false;
        }
        else
        {
            string strSalt = (string)objDR["Salt"];
            string strStoredPassword = (string)objDR["Pass"];
            bool boolActive = (bool)objDR["Active"];
            string strGivenPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(strSalt + Password, "SHA1");
            return strStoredPassword == strGivenPassword;
        }
    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        string usrName;
        if (CheckCredentials(txtUsername.Text, txtPassword.Text) == true)
        {
            Session.Add("usrName", txtUsername.Text);
            if (rememberMe.Checked)
            {
                HttpCookie myCookie = new HttpCookie("usrName");
                myCookie.Value = txtUsername.Text;
                myCookie.Expires = DateTime.Now.AddDays(365d);
                Response.Cookies.Add(myCookie);
            }
            Response.Redirect("SessLog.aspx");
        }
        else
        {
            lblCheck.Text = "You entered the wrong credentials!";
        }
    }

Open in new window

0
 
LVL 1

Expert Comment

by:trenduin
ID: 21952302
You need to add the "Active" field in you select statement and then do something like this:

string strSalt = (string)objDR["Salt"];
            string strStoredPassword = (string)objDR["Pass"];
            bool boolActive = (bool)objDR["Active"];
 
if(boolActive)
{
            string strGivenPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(strSalt + Password, "SHA1");
            return strStoredPassword == strGivenPassword;
}else{
    return false;
}

Open in new window

0
 

Author Comment

by:introlux
ID: 21952417
Thanks that worked!

I have another open question if you dont mind having a look at it if you can help:

http://www.experts-exchange.com/Microsoft/Development/.NET/Visual_Studio_.NET_2005/Q_23543422.html

Thanks again,

introlux
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.

688 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question