User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the ASP.NET section within the Web Development category of DaniWeb, a massive community of 361,566 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,058 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our ASP.NET advertiser: Lunarpages ASP Web Hosting
Views: 133559 | Replies: 145
Reply
Join Date: Mar 2005
Posts: 5
Reputation: vbmntv is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 0
vbmntv vbmntv is offline Offline
Newbie Poster

Re: Updated : Simple ASP.Net Login Page

  #21  
Apr 1st, 2005
Paladine: I am not sure...has anyone had asked you this question or not. ...I did not all the posts.
As the way it code, if I know what the next page is such as Default.aspx ..I don't have to login...I can type the URL and it goes direct to that page. How can we prevent that? Thanks so much for your response.
(sorry, I am so new with this stuff).
Reply With Quote  
Join Date: Feb 2003
Location: Canada
Posts: 786
Reputation: Paladine has a spectacular aura about Paladine has a spectacular aura about Paladine has a spectacular aura about 
Rep Power: 9
Solved Threads: 26
Colleague
Paladine's Avatar
Paladine Paladine is offline Offline
Master Poster

Re: Updated : Simple ASP.Net Login Page

  #22  
Apr 2nd, 2005
Ok, I have had a number of people ask me how to prevent access to say the default.aspx page via the direct url, and you can prevent this in a number of ways. I have mentioned the use of cookies, but in the following example I will use another method of Session variables.

Continue from the existing code in this tutorial and add the following.

Open the Global.asax file and view the code. This file contains many elements, and the one we are going to focus on is the Session_Start subroutine.

	Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
		' Fires when the session is started
	End Sub
	
 

Add the follow line of code to this subroutine.

		 '   <summary>
		 '	   Track whether they're logged in or not
		 '   </summary>
		Session("Logged_IN") = "No"
 

This will setup a Session level variable to determine if the user has successfully logged in or not.

Now to the default.aspx page or your equivalent page to this (and any other pages within your application) add the following lines of code in the Page_Load subroutine.

 Response.Cache.SetCacheability(HttpCacheability.NoCache)
		 If Session("Logged_IN").Equals("No") Then
			 Response.Redirect("Login.aspx")
		End If
 

These lines do several things. The first line sets the page to not be cacheable. Meaning it will not be stored in the cache of the users computer. Why? Well then the user could still reach the page and appear to be logged in, but would actually be, and would not be able to access any of the functionality the page may have. So lets just avoid this by not making it cacheable.

The next few lines do the testing to see if the user is logged in or not. If not, then the user is directed to the Login.aspx page.

Few things to note:
1. All objects inherit the method Equals() for comparing two objects.
2. All objects inherit the ToString method
These methods are inherited from the Object Parent Class.


So my Page_Load event would look something like this:

	 Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
			 'Put user code to initialize the page here
			 '   <summary>
			 ' ||||| Authenicate user for accces to pages within application
			 ' ||||| Enusre the page can't be navigated to without
			 '   |||||   user's being online and logged in.
			 ' ||||| **Note: Logged_IN session object is created in Session_Start 
			 '   |||||   of the Global.asax file **
			 ' ||||| Rem: All Objects inherit Equals() // compare two objects // ToString()
			 '   |||||   methods from the Object Parent Class
			 '   </summary>
			 '   |Do not allow caching of page
			 Response.Cache.SetCacheability(HttpCacheability.NoCache)
			 If Session("Logged_IN").Equals("No") Then
				 Response.Redirect("Login.aspx")
			 End If
	End Sub
 


Now there is only one thing left to do. You have to add a line of code to your Login.aspx to set the Session variable to "Yes" when the user has successfully logged in.

So this modification is made to the cmdSubmit_Click subroutine where the condition statement If DBConnection(txtUserName.Text.Trim(), txtPassword.Text.Trim()) Then exists. So my updated subroutine would look like this:

 Private Sub cmdSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSubmit.Click
		 If Page.IsValid Then    '   ||||| Meaning the Control Validation was successful!
			 ' ||||| Connect to Database for User Validation |||||
			 If DBConnection(txtUserName.Text.Trim(), txtPassword.Text.Trim()) Then
				 Session("Logged_IN") = "Yes"    '   |||||   Use to Validate on other pages in the application
				 FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, False)  '   |||||   default.aspx Page!
			 Else
				 '   |||||   Credentials are Invalid
				 lblMessage.Text = "Invalid Login!"
			 End If
		 End If
	End Sub
 

** Please Note it is very important that you place the line of code Session("Logged_IN") = "Yes" right before the RedirectFromLoginPage method call, because your session variable must be set before you redirect the user...or else they will never register as being logged in or your default.aspx or other pages.

Hope this helps everyone.

Happy Coding!

:cool
Assistant Manager, Regional Pharmacy Information Systems
TLC Services Website (Under Construction)
Updated : ASP.Net Login Code
Reply With Quote  
Join Date: Mar 2005
Posts: 5
Reputation: vbmntv is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 0
vbmntv vbmntv is offline Offline
Newbie Poster

Re: Updated : Simple ASP.Net Login Page

  #23  
Apr 4th, 2005
Paladine: Thanks so much for your generous help. It works great

Now, we can login and view the default page. What about LogOut? Have you tried that Paladine? it would be great if you can give us a hint ....thanks again.
Reply With Quote  
Join Date: Feb 2003
Location: Canada
Posts: 786
Reputation: Paladine has a spectacular aura about Paladine has a spectacular aura about Paladine has a spectacular aura about 
Rep Power: 9
Solved Threads: 26
Colleague
Paladine's Avatar
Paladine Paladine is offline Offline
Master Poster

Re: Updated : Simple ASP.Net Login Page

  #24  
Apr 4th, 2005
Hey no problem. Glad I could help!

So, for logout what do you want that is causing you issues?

I would just have a button or hyperlink that the user would click to logout, and in the event of On_Click set the Session variable to "No" and redirect the user to the login page again.

Hope this helps.

Originally Posted by vbmntv
Paladine: Thanks so much for your generous help. It works great

Now, we can login and view the default page. What about LogOut? Have you tried that Paladine? it would be great if you can give us a hint ....thanks again.
Assistant Manager, Regional Pharmacy Information Systems
TLC Services Website (Under Construction)
Updated : ASP.Net Login Code
Reply With Quote  
Join Date: Apr 2005
Location: Tennessee
Posts: 18
Reputation: millers_35 is an unknown quantity at this point 
Rep Power: 4
Solved Threads: 1
millers_35 millers_35 is offline Offline
Newbie Poster

Re: Updated : Simple ASP.Net Login Page

  #25  
Apr 6th, 2005
Ok guys I have been working on this for hours and I still cant figure out what the problem is. So here is my setup

web.config

<appSettings>
		<add key="strConn" value="Provider = Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Administrator\My Documents\tke\bin\Database.mdb;User ID=Admin;Password=;" />
	</appSettings>
<authentication mode="Forms">
			<forms name="DBLogin" loginUrl="login.aspx" /> 
		</authentication>

Each user has a unique "Scroll #" so my access procedure looks like this. If I run this procedure within access it does return the appropiate value.
SELECT scroll_numb
FROM tbl_alumni_login
WHERE (((username)=[@UserName]) AND ((Password)=[@Password]));

and the table "tbl_alumni_login" has 3 columns 1.scroll_numb 2. username 3. password


login.aspx Database connection "Pretty much just like you have yours"
Function DBConnection(ByVal strUserName As String, ByVal strPassword As String) As Boolean

Dim MyConn As OleDbConnection = New OleDbConnection(ConfigurationSettings.AppSettings("strConn"))
Dim MyCmd As New OleDbCommand("sp_alumni_login", MyConn)
        MyCmd.CommandType = CommandType.StoredProcedure

Dim objParam1, objParam2 As OleDbParameter

objParam1 = MyCmd.Parameters.Add("@UserName", OleDbType.Char)
objParam2 = MyCmd.Parameters.Add("@Password", OleDbType.Char)

objParam1.Direction = ParameterDirection.Input
objParam2.Direction = ParameterDirection.Input
        
objParam1.Value = txtUserName.Text
objParam2.Value = txtPassword.Text


Try
            If MyConn.State = ConnectionState.Closed Then
                   MyConn.Open()
            End If

            Dim objReader As OleDbDataReader
            objReader = MyCmd.ExecuteReader(CommandBehavior.CloseConnection)

            While objReader.Read()

                If CStr(objReader.GetValue(0)) <> "1" Then
                    lblMessage.Text = "Invalid Login!"
                Else
                    objReader.Close()  
                    Return True
                End If
            End While
        Catch ex As Exception
            lblMessage.Text = "Error Connecting to Database!"
        End Try


    End Function


login.aspx submit button "Same as yours as well"

If Page.IsValid Then   

            Dim intMaxLoginAttempts = CInt(Session("Num_of_Tries"))

            If DBConnection(txtUserName.Text.Trim(), txtPassword.Text.Trim()) Then
                Session("Logged_IN") = "Yes"    
                FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, False) 
            Else
                 lblMessage.Text = "Invalid Login!" 
                Session("LoginCount") = CInt(Session("LoginCount")) + 1
              
                If Session("LoginCount").Equals(intMaxLoginAttempts) Then
                    Response.Redirect("Denied.aspx")
                End If

                If CInt(Session("Num_of_Tries")) > 2 Then   
                    Response.Redirect("Denied.aspx")
                End If

            End If
        End If

default.aspx load event as well for all the other forms I have
Response.Cache.SetCacheability(HttpCacheability.NoCache)
        If Session("Logged_IN").Equals("No") Then
            Response.Redirect("login.aspx")
        End If

global.asax session start "Same as yours again"
Session("Num_of_Tries") = 3
        Session("LoginCount") = 0
        Session("Logged_IN") = "No"


So I think my problem is within the parameter Session("Logged_IN") = "Yes" passed into global.asax. Because everytime I have the code for the default.aspx load event in there it just automatically redirects me straight back to the login page with no "Invalid input" message. However if I enter a completely wrong username and password and get redirected to denied.aspx then go back and put in the correct username and pass I get redirected to the default page, even if the logged in check is in the page load.

If I do get directed to the default page and then start navigating within my application between different pages it will kick me back out to the login page.

I dont know what I have wrong but if you all could help me out it would be greatly appreciated.

Miller
Reply With Quote  
Join Date: Feb 2003
Location: Canada
Posts: 786
Reputation: Paladine has a spectacular aura about Paladine has a spectacular aura about Paladine has a spectacular aura about 
Rep Power: 9
Solved Threads: 26
Colleague
Paladine's Avatar
Paladine Paladine is offline Offline
Master Poster

Re: Updated : Simple ASP.Net Login Page

  #26  
Apr 6th, 2005
OK, I think I may have the problem figured out. My question is this: What value could scroll_numb be? Would it ever be 0, 2, 3, 4, 5, etc and not 1?? From the code you have provided that it seems the scroll_numb is like my ID column, which will never just be 1!

So you seem to be returning the value of scroll_numb and then in the code
 If CStr(objReader.GetValue(0)) <> "1" Then
				    lblMessage.Text = "Invalid Login!"
				Else
...
You are comparing the value in scroll_numb to see if it is NOT "1", which i probably may never be. So the DBConnection returns FALSE and Invalid Login.


Hope that makes sense, and it seems to be the issue you are having.
Assistant Manager, Regional Pharmacy Information Systems
TLC Services Website (Under Construction)
Updated : ASP.Net Login Code
Reply With Quote  
Join Date: Apr 2005
Location: Tennessee
Posts: 18
Reputation: millers_35 is an unknown quantity at this point 
Rep Power: 4
Solved Threads: 1
millers_35 millers_35 is offline Offline
Newbie Poster

Re: Updated : Simple ASP.Net Login Page

  #27  
Apr 6th, 2005
I think I get what you are saying so this the way I have it now would only work if the scroll number was 1 and would work if the number was like 200?

If CStr(objReader.GetValue(0)) <> "1" Then
                    lblMessage.Text = "Invalid Login!"

I will be using 1 but not anything less than 1. I will be using like 1 - 700. So should this do the trick?

If CStr(objReader.GetValue(0)) < "1" Then
                    lblMessage.Text = "Invalid Login!"

I may be interpreting the code wrong but I dont know I have tried this < "1" and it still doesnt seem to work as I am still getting redirected back to the login page.

I appreciate the help I have been pulling my hair out over this 1. I do like the idea of using access procedures tho, I had no idea u could do that but it does seem easier.

Miller
Reply With Quote  
Join Date: Apr 2005
Location: Tennessee
Posts: 18
Reputation: millers_35 is an unknown quantity at this point 
Rep Power: 4
Solved Threads: 1
millers_35 millers_35 is offline Offline
Newbie Poster

Re: Updated : Simple ASP.Net Login Page

  #28  
Apr 6th, 2005
Ok I setup breakpoints throught my app in the login DB function and within the page load of the default page. It makes it all the way through the login page and into the default page load where then it checks
If Session("Logged_IN").Equals("No") Then
            Response.Redirect("login.aspx")
and it doesnt make it to the
Else
            Session("Logged_IN") = "Yes"

So there for as far as my understanding its not passing that parameter Session("Logged_IN") = "Yes" from the login page to the Global.asax Session start.

Is that right or am I totally off? Also how do I check the value of Session("Logged_IN")?

edit:
Ok I setup a label on the login page and on the default page to display the session("Logged_IN") value. k when the login page loads it says "No" ; after I login I have it display again after setting session("Logged_IN") = "Yes" and the lable does indeed display "Yes". So now its in the processes of redirecting me to default.aspx and I have it display a label again to see what the value is and it is "No". So that value in Session Start is not staying at "Yes" during the transfer from login.aspx to default.aspx. And I am trying to find out why but am unsuccessful.

Miller
Reply With Quote  
Join Date: Feb 2003
Location: Canada
Posts: 786
Reputation: Paladine has a spectacular aura about Paladine has a spectacular aura about Paladine has a spectacular aura about 
Rep Power: 9
Solved Threads: 26
Colleague
Paladine's Avatar
Paladine Paladine is offline Offline
Master Poster

Re: Updated : Simple ASP.Net Login Page

  #29  
Apr 6th, 2005
Well there maybe an issue with it being a string. So change the line to be

CInt(objReader.GetValue(0)) < 1

And also you would not have an Else part to the if statement in the default.aspx page. Not that it is the issue.

And what does your session_start and session_end look like in the global.asax file?

If the problem isn't there, I am at loss. You could send me a PM with the code sections in it and I could review them. Something is reseting that Session variable for some reason. I am guessing in the Session_Start or End? I can't seem to see where the problem is according to your code. And you have copied my code in line by line to very it works....?

Oh and just to clarify:
So there for as far as my understanding its not passing that parameter Session("Logged_IN") = "Yes" from the login page to the Global.asax Session start.

No value is passed to or from the Global.asax Session_Start. That subroutine only creates the variable and populates it on start of a session. But I understand what you are referring to.

Nice work on the the breakpoints and finding out what value in the Session variable is at different points. Well done.

But saying that.....I am still at a loss here. I will take a clearer look at it when I get home!
Assistant Manager, Regional Pharmacy Information Systems
TLC Services Website (Under Construction)
Updated : ASP.Net Login Code
Reply With Quote  
Join Date: Apr 2005
Location: Tennessee
Posts: 18
Reputation: millers_35 is an unknown quantity at this point 
Rep Power: 4
Solved Threads: 1
millers_35 millers_35 is offline Offline
Newbie Poster

Re: Updated : Simple ASP.Net Login Page

  #30  
Apr 6th, 2005
The thing is tho is that its getting past the
If Cstr(objReader.GetValue(0)) < "1" Then

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the session is started
        '<summary>
        '   |Fires when the session is started
        '   |Administrator will only be allowed a certain number of login attempts
        '</summary>
        Session("Num_of_Tries") = 3
        Session("LoginCount") = 0

        '   |Track whether they're logged in or not
        Session("Logged_IN") = "No"
    End Sub

And I have nothing in Session End. I have to go meet with my client right now but will be back shortly to try and work this out and let you see my code blocks. I appreciate your help!


edit: Yes it is passing the value "Yes" into Global.asax until it redirects to default.aspx and then it resets it to "No"
Miller
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

DaniWeb ASP.NET Marketplace
Thread Tools Display Modes

Similar Threads
Other Threads in the ASP.NET Forum

All times are GMT -4. The time now is 3:03 am.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC