Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 520
  • Last Modified:

Creating a login for Asp.Net

Hi there,

I have created a login interface for asp but I need to use asp.net for the database so I am in the process of creating

My version of Asp is unfortunately 1.1 and convincing Brinkster to up it to 2.0 is not that easy as they say it's too unstable!

Anyway...

I was wondering whether somebody would be able to point me in the direction of some good code for logging in (preferably put it in the page!)


My current code:

log_in.asp (included from login.aspx)

<%response.buffer = false%>
<%
Dim Conn_CONNECTIONSTRING
Dim Conn = Server.CreateObject("ADODB.Connection")
Dim objRecordset1
Conn.CONNECTIONSTRING = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" & Server.Mappath("../admin.mdb") & ";"
Conn.Open

If request.form("login") = "yes" then
  dim sqltemp
  sqltemp="select * from tblConfig where username='"
  sqltemp=sqltemp & request.form("username") & "'"
  sqltemp=sqltemp & "AND password='"
  sqltemp=sqltemp & request.form("password") & "'"
  dim rstemp=Conn.execute(SQLTemp)

    If NOT rstemp.eof then
      session("logged_in") = "True"
      response.redirect("index.asp")
    Else
      response.write("Invalid Username")
    End If
end if

%>

<html>
  <head>
    <title>Admin Login</title>
  </head>
  <body bgcolor=ffffff valign="top">

    <form name="form1" method="post" action="login.aspx">
      <b>Username</b><br>
        <input type="text" name="username"><br><br>
      <b>Password<br>
        <input type="password" name="password">
      <input type="hidden" name="login" value="yes"><br>
      <br>
      <input type="submit" name="Submit2" value="Submit">
      <br>
    </form>
  </body>
</html>

loginchecker.asp (used to authenticate users in subsequent pages)

<% Response.Buffer = True %>

<%
If session("logged_in") <> "True" Then
  Response.Redirect("log_in.asp")
End If
%>

Am I maybe calling the wrong page login.aspx?

If any of this can be re-used that would be great.

Thanks in advance.
0
DanBAtkinson
Asked:
DanBAtkinson
  • 29
  • 18
2 Solutions
 
fahimnxbCommented:
Dear DanBAtkinson,

Following links contain source code for ASP.NET login screen.

http://www.daniweb.com/techtalkforums/thread6028.html (this is really good and explonatory enough to understand)

If still unclear also have a look with involving Java script too...

http://authors.aspalliance.com/aspguru/aspnet.aspx?Type=Art&ArtID=927

And the last option is; if still you need some thing more customized then let me know, and I will write some idea generating code for you.

Regards,
Me

0
 
DanBAtkinsonAuthor Commented:
Thanks for that link. Is there no simpler method of writing an ASP.NET login that doesn't involve all of that code?

I was hoping that it would be simple to use.

The JS link seems closer to the mark but what I'd really like to know is if my code can be modified so that it can run in ASP.NET.
0
 
davidlars99Commented:
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data" %>
<HTML>
<HEAD>
<Script Language="VB" Runat="Server">

Public Sub LoginUser(sender As Object, e As System.EventArgs)
      Dim login As Integer=Authenticate(username.Text, Password.Text)

      If login>0 Then
            FormsAuthentication.RedirectFromLoginPage(username.Text, False)
      End If
End Sub

Function Authenticate(uid As String, pwd As String) As Integer
      Dim con As New SqlConnection( _
            ConfigurationSettings.AppSettings("conn")), _
            cmd As SqlCommand, _
            rdr As SqlDataReader, _
            rtn As Integer
      
      cmd=New SqlCommand("Login", con)
      cmd.CommandType=CommandType.StoredProcedure
      cmd.Parameters.Add("@username", SqlDbType.Varchar)
      cmd.Parameters("@username").Value=uid
      cmd.Parameters.Add("@password", SqlDbType.Varchar)
      cmd.Parameters("@password").Value=pwd
      cmd.Parameters.Add("@Login", SqlDbType.Int)
      cmd.Parameters("@Login").Direction=ParameterDirection.Output
      
      con.Open()
      cmd.ExecuteScalar()
      rtn=cmd.Parameters("@Login").Value
      con.Close()
      
      Return rtn
End Function

</Script>
<TITLE>ASP.NET Project</TITLE>
<link href="styles.css" rel="stylesheet">
</HEAD>
<BODY>
<table width="100%" border="0" cellpadding="0" cellspacing="0" background="images/header_bg.gif">
      <tr>
            <td><img src="images/header_top.gif"></td>
      </tr>
</table>
<table with="100%" border="0" cellpadding="0" cellspacing="0">
      <tr>
            <td width="157"><img src="images/header_bottom.gif"></td>
            <td></td>
      </tr>
</table>
<table with="100%" border="0" cellpadding="0" cellspacing="0">
      <tr>
            <td valign="top" width="160">
                  &nbsp;
            </td>
            <td valign="top">
                  <h1>Login: </h1>
                  <form runat="server">
                        <p>Username:<br><asp:textbox id="username" size="20" runat="server" textmode="singleline" /></p>
                        <p>Password:<br><asp:textbox id="password" size="21" runat="server" textmode="password" /></p>
                        <br>
                        <p><asp:button id="btn1" text="Login" onclick="LoginUser" runat="server" /></p>
                  </form>
            </td>
      </tr>
</table>      
</BODY>
</HTML>


than create table with two columns "Username" and "Password", create a stored procedure as well which will return 1 if login's good and 0 if fails
0
Microsoft Certification Exam 74-409

VeeamĀ® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

 
DanBAtkinsonAuthor Commented:
I'm not sure why:

 Comment from fahimnxb
Date: 03/19/2005 05:52PM GMT
 Comment  


Dear DanBAtkinson,

Following links contain source code for ASP.NET login screen.

http://www.daniweb.com/techtalkforums/thread6028.html (this is really good and explonatory enough to understand)

If still unclear also have a look with involving Java script too...

http://authors.aspalliance.com/aspguru/aspnet.aspx?Type=Art&ArtID=927

And the last option is; if still you need some thing more customized then let me know, and I will write some idea generating code for you.

Regards,
Me


 
Comment from DanBAtkinson
Date: 03/19/2005 06:09PM GMT
 Your Comment  


Thanks for that link. Is there no simpler method of writing an ASP.NET login that doesn't involve all of that code?

I was hoping that it would be simple to use.

The JS link seems closer to the mark but what I'd really like to know is if my code can be modified so that it can run in ASP.NET.
 
Comment from davidlars99
Date: 03/19/2005 09:22PM GMT
 Comment  


<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data" %>
<HTML>
<HEAD>
<Script Language="VB" Runat="Server">

Public Sub LoginUser(sender As Object, e As System.EventArgs)
     Dim login As Integer=Authenticate(username.Text, Password.Text)

     If login>0 Then
          FormsAuthentication.RedirectFromLoginPage(username.Text, False)
     End If
End Sub

Function Authenticate(uid As String, pwd As String) As Integer
     Dim con As New SqlConnection( _
          ConfigurationSettings.AppSettings("conn")), _
          cmd As SqlCommand, _
          rdr As SqlDataReader, _
          rtn As Integer
     
     cmd=New SqlCommand("Login", con)
     cmd.CommandType=CommandType.StoredProcedure
     cmd.Parameters.Add("@username", SqlDbType.Varchar)
     cmd.Parameters("@username").Value=uid
     cmd.Parameters.Add("@password", SqlDbType.Varchar)
     cmd.Parameters("@password").Value=pwd
     cmd.Parameters.Add("@Login", SqlDbType.Int)
     cmd.Parameters("@Login").Direction=ParameterDirection.Output
     
     con.Open()
     cmd.ExecuteScalar()
     rtn=cmd.Parameters("@Login").Value
     con.Close()
     
     Return rtn
End Function

</Script>
<TITLE>ASP.NET Project</TITLE>
<link href="styles.css" rel="stylesheet">
</HEAD>
<BODY>
<table width="100%" border="0" cellpadding="0" cellspacing="0" background="images/header_bg.gif">
     <tr>
          <td><img src="images/header_top.gif"></td>
     </tr>
</table>
<table with="100%" border="0" cellpadding="0" cellspacing="0">
     <tr>
          <td width="157"><img src="images/header_bottom.gif"></td>
          <td></td>
     </tr>
</table>
<table with="100%" border="0" cellpadding="0" cellspacing="0">
     <tr>
          <td valign="top" width="160">
               &nbsp;
          </td>
          <td valign="top">
 

is needed but ok! :)

I can't see where the db is opened (there is no reference to a db file in that.

About creating a stored proc also... I'm not familiar with this. What do you mean exactly?
0
 
DanBAtkinsonAuthor Commented:
Ooops.

Wasn't sure where this comes from:

<table width="100%" border="0" cellpadding="0" cellspacing="0" background="images/header_bg.gif">
     <tr>
          <td><img src="images/header_top.gif"></td>
     </tr>
</table>
<table with="100%" border="0" cellpadding="0" cellspacing="0">
     <tr>
          <td width="157"><img src="images/header_bottom.gif"></td>
          <td></td>
     </tr>
</table>
<table with="100%" border="0" cellpadding="0" cellspacing="0">
     <tr>
          <td valign="top" width="160">
               &nbsp;
          </td>
          <td valign="top">
 

I can't see where the db is opened (there is no reference to a db file in that.

About creating a stored proc also... I'm not familiar with this. What do you mean exactly?
0
 
davidlars99Commented:
this is what should be used with that



Create Table Users (
      UserName varchar(25),
      Password varchar(8)
)

Insert Into Users (UserName,Password) Values ('davidlars99','password')

Create  Procedure Login
      @userName varchar(25),
      @password varchar(8),
      @code int out
As
      Select @code=count(*) from users
      where username=@username and password=@password
      
GO
0
 
davidlars99Commented:
and instead of

Dim con As New SqlConnection(ConfigurationSettings.AppSettings("conn"))

use

Dim con As New SqlConnection("data source=localhost;uid=username;pwd=password;initial catalog=table")

or

Dim con As New SqlConnection("data source=localhost; integrated security=SSPI; initial catalog=table")
0
 
DanBAtkinsonAuthor Commented:
But that's inserting data into the database isn't it?

I just want to check it.
0
 
davidlars99Commented:
ok let me break it down for you


[ASP.NET Login Page]

<Script Language="VB" Runat="Server">

Public Sub LoginUser(sender As Object, e As System.EventArgs)
     Dim login As Integer=Authenticate(username.Text, Password.Text)

     If login>0 Then
          FormsAuthentication.RedirectFromLoginPage(username.Text, False)
     End If
End Sub

Function Authenticate(uid As String, pwd As String) As Integer
     Dim con As New SqlConnection("data source=localhost;uid=username;pwd=password;initial catalog=table"), _
          cmd As SqlCommand, _
          rdr As SqlDataReader, _
          rtn As Integer
     
     cmd=New SqlCommand("Login", con)
     cmd.CommandType=CommandType.StoredProcedure
     cmd.Parameters.Add("@username", SqlDbType.Varchar)
     cmd.Parameters("@username").Value=uid
     cmd.Parameters.Add("@password", SqlDbType.Varchar)
     cmd.Parameters("@password").Value=pwd
     cmd.Parameters.Add("@Login", SqlDbType.Int)
     cmd.Parameters("@Login").Direction=ParameterDirection.Output
     
     con.Open()
     cmd.ExecuteScalar()
     rtn=cmd.Parameters("@Login").Value
     con.Close()
     
     Return rtn
End Function

</Script>

--------------------------------------------------------------------------------------------


[SQL Database Table]

Create Table Users (
     UserName varchar(25),
     Password varchar(8)
)

-------------------------------------------------------------------------------------------


[SQL Stored Precedure]

Create  Procedure Login
     @userName varchar(25),
     @password varchar(8),
     @code int out
As
     Select @code=count(*) from users
     where username=@username and password=@password
     
GO
0
 
davidlars99Commented:
oh yes almost forgot, instead of "@Login" use "@code"
0
 
DanBAtkinsonAuthor Commented:
Sorry. I meant that I've never ever used stored procedures before.

I've looked into that but I have a question. At no point in that above example is an Access database called (at least I can't find one).

You said you'd break it down for me I don't have an SQL table, I'm not using an SQL db, just queries.
0
 
DanBAtkinsonAuthor Commented:
Or rather MS SQL queries.
0
 
DanBAtkinsonAuthor Commented:
Oh dear.

Please forgive me. It's Sunday morning and I'm not feeling very well.
0
 
davidlars99Commented:
ok since you don't have SQL database lets strart it out by creating a login page like so and we'll do the rest when I come back on monday


<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDB" %>
<HTML>
<HEAD>
<Script Language="VB" Runat="Server">

Public Sub LoginUser(sender As Object, e As System.EventArgs)
 
End Sub

Function Authenticate(uid As String, pwd As String) As Integer
 
End Function

</Script>
<TITLE>ASP.NET Login</TITLE>
</HEAD>
<BODY>
<table with="100%" border="0" cellpadding="0" cellspacing="0">
     <tr>
          <td valign="top">
               <h1> Login: </h1>
               <form runat="server">
                    <p>Username:<br><asp:textbox id="username" size="20" runat="server" textmode="singleline" /></p>
                    <p>Password:<br><asp:textbox id="password" size="21" runat="server" textmode="password" /></p>
                    <br>
                    <p><asp:button id="btn1" text="Login" onclick="LoginUser" runat="server" /></p>
               </form>
          </td>
     </tr>
</table>    
</BODY>
</HTML>
0
 
DanBAtkinsonAuthor Commented:
Thanks.

I have something along the lines of:

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDB" %>

<html>
  <head>
    <Script Language="VB" Runat="Server">

      sub Page_Load
        dim dbconn
        dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & server.mappath("admin.mdb"))
        dbconn.Open()
        dim sql="SELECT * FROM tblConfig"
        dim Cmd As OleDbCommand = New OleDbCommand(sql,dbconn)
        dim reader As OleDbDataReader
        reader = Cmd.ExecuteReader()
        dbconn.Close()
      end sub

      Public Sub LoginUser(sender As Object, e As System.EventArgs)

      End Sub

      Function Authenticate(uid As String, pwd As String) As Integer
 
      End Function

    </script>
    <title>Admin Login</title>
  </head>

  <body>

  <form runat="server">
    <table border="1">
    <th>
    Username:</b><asp:TextBox id="username" runat="server" /><br>
    Password:</b><asp:TextBox id="password" TextMode="password" runat="server" /><br>
    <asp:Button OnClick="LoginUser" Text="Submit" runat="server" />
    </th>
    </table>
  </form>

  </body>
</html>


Because of my currently limited knowledge of .net, I assume that by placing the dbconnections into the web.config file, you remove the possibility for hacking as the location of the database is hidden from the page itself. I may be wrong but I've only been doing Asp.net properly for a week at best.

I think Brinkster insists that the web.config file be placed in the webroot of the site which is annoying because my admin area is about 4 levels down from the root.

My main problem with the last login (which was all asp based) was that for some reason the session variable 'logged_in' was not passed on past the first page and would not work with asp.net pages.

I'd also just like to say thanks for your patience, it is appreciated.
0
 
DanBAtkinsonAuthor Commented:
Just wondering whether you had had a chance to come back to this yet.
0
 
davidlars99Commented:
ok, you said you have access database right..? create table with 2 columns

Username  
Password


both should be text columns
0
 
DanBAtkinsonAuthor Commented:
I've done that.
0
 
DanBAtkinsonAuthor Commented:
The table is called tblConfig.
0
 
davidlars99Commented:
create "web.config" file and put this code in

<configuration>      
   <system.web>                  
      <compilation debug="true" />
      <authentication mode="Forms">
           <forms name="myLoginCookie" loginUrl="login.aspx" slidingExpiration="true">
            <authorization>
              <deny users="?" />
            </authorization>
           </forms>
        </authentication>
   </system.web>
</configuration>
0
 
DanBAtkinsonAuthor Commented:
Done!
0
 
davidlars99Commented:
sorry use this one

<configuration>    
   <system.web>              
      <compilation debug="true" />
      <authentication mode="Forms">
           <forms name="myLoginCookie" loginUrl="login.aspx" slidingExpiration="true">
              <credentials passwordFormat="Clear" />
           </forms>
           <authorization>
             <deny users="?" />
           </authorization>
        </authentication>
   </system.web>
</configuration>
0
 
DanBAtkinsonAuthor Commented:
Done!
0
 
DanBAtkinsonAuthor Commented:
Um... Is there anything else?
0
 
DanBAtkinsonAuthor Commented:
davidlars99: is there any way you could continue this as I would like to get the asp.net admin area up and running as soon as possible.

Thanks.
0
 
DanBAtkinsonAuthor Commented:
Is there anybody else who could possibly finish this off at all???

Thanks.
0
 
davidlars99Commented:
I'll come back to this later this afternoon until than you have to be patient, sorry it's my work schedule not me...  :)
0
 
DanBAtkinsonAuthor Commented:
Apologies. I thought you'd deserted me! :>
0
 
davidlars99Commented:
ok replace two previous blank functions named "LoginUser" and "Authenticate" with these new ones


   Public Sub LoginUser(ByVal sender As Object, ByVal e As System.EventArgs)
        If Authenticate(txtUserName.Text, txtPassword.Text) > 0 Then
            FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, True)
        End If
    End Sub

    Function Authenticate(ByVal userName As String, ByVal password As String) As Integer
        Dim cn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("admin.mdb"))
        Dim cmd As OleDbCommand = New OleDbCommand("SELECT Count(*) FROM tblConfig WHERE Username=@username AND Password=@password", cn)

        cmd.Parameters.Add("@username", userName)
        cmd.Parameters.Add("@password", password)

        cn.Open()
        Dim status As Integer = cmd.ExecuteScalar()
        cn.Close()

        Return status
    End Function
0
 
DanBAtkinsonAuthor Commented:
Ok. I've written that into it thanks.
0
 
DanBAtkinsonAuthor Commented:
I'm sure that you're busy or something but was there anything else I need to add?

Say if I go to another page and the authenticity of the user needs to be verified perhaps?

Thanks.
0
 
davidlars99Commented:
default expiration time is 30 minutes and you can visit any page during that time, after 30 minutes it will renew itself because in your web.config file you have "slidingExpiration" attribute set to "true". Also I suggest you read some materials on the web such as this one

part 1
http://www.15seconds.com/issue/020220.htm

part2
http://www.15seconds.com/issue/020305.htm
0
 
DanBAtkinsonAuthor Commented:
Ok. Thankyou for those sources.

I receive the following error when I run it:

It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.
0
 
DanBAtkinsonAuthor Commented:
Although putting the web.config file in the webroot (as the host suggests) helps.

When I run that, I get the error:

'Unrecognized tag 'authorization' in the config file' pointing to:
<authorization>

Any ideas/suggestions please?
0
 
DanBAtkinsonAuthor Commented:
Fixed that problem by closing the authentication tags before the form.

The login window now works but it (eventually) takes me to this page on the website:

www.mysite.com/login.aspx?ReturnUrl=%2fproject%2fv1%2fadmin%2fnewlog%2flogin.aspx

My login page is stored in mysite.com/project/v1/admin/newlog/login.aspx (although once the login works it will be moved to another directory.

Is there anything I can do?
0
 
davidlars99Commented:
my fault "<authorization>" tag should not be declared inside "<authentication>", replace whole thing with this one

<configuration>
  <system.web>
    <authentication mode="Forms">
      <forms name="myLoginCookie" loginUrl="login.aspx" slidingExpiration="true">
          <credentials passwordFormat="Clear" />
       </forms>
    </authentication>
    <authorization>
      <deny users="?" />
    </authorization>
  </system.web>
</configuration>


and as far as you error "...virtual directory not being configured as an application in IIS..." concerned it is caused exactly by what it says and here's how to fix it:

1. right click on My Computer icon
2. select Manage and IIS administration window will open up
3. exand Services and Application
4. exand Internet Information Services and select Default Web Site
5. find the folder where your authentication project is located and right click on it
6. click on Properties and when properties windows opens up you'll see button named "Create" click on it and you're good to go




0
 
davidlars99Commented:
if you are working with visual studio .net then you don't have to worry about these things, but if you manualy creating all the pages than you have to follow these steps
0
 
DanBAtkinsonAuthor Commented:
I'm not working with VS.Net. Everything I've been doing has been solely in Notepad. I don't have IIS installed on my computer. Do I need it?

I've just been uploading the files to my webhost (Brinkster).
0
 
davidlars99Commented:
is everything what we have been doing here working...? then don't worry..! and no, you don't need IIS unless "*.aspx" are served on your local computer
0
 
DanBAtkinsonAuthor Commented:
No. It doesn't appear to be working. If it was I would have accepted your code! It appears that the original login.aspx has some problems (mainly due to txtUsername and txtPassword not being declared). I changed these to the ones in the textboxes.

The login box now works but redirects to default.aspx on my webroot. Where is the redirect code for this so that I can edit the directory and page?

And what authetication code do I need when I go to another page?
0
 
davidlars99Commented:
there is no redirect code, that's the way ASP.NET works when you are authenticated from "login.aspx"
0
 
DanBAtkinsonAuthor Commented:
Thanks. It automatically redirects to default.aspx on the webroot no matter what? Don't get me wrong but isn't there a way to change the redirect?
0
 
DanBAtkinsonAuthor Commented:
I've set up a basic response.redirect to the right directory.

The problem with authenticating users going to pages after logging in. How does the page confirm whether the user is still genuine?

I mean a login checker such as:
<%
If session("logged_in") <> "True" Then
  Response.Redirect("log_in.asp")
End If
%>
0
 
DanBAtkinsonAuthor Commented:
Right. It's 10 minutes before I leave for Easter, this has been doing for 5 days now so it's time to wrap it up.

I think it's fair to say that davidlars99 has won the points. I'll open up another question on Tuesday regarding a authenticity checker (probably along the lines of:

Sub Page_Load()
  If User.Identity.IsAuthenticated Then
    displayCredentials.InnerHtml = "Current User : <b>" & User.Identity.Name & "</b><br><br>Authentication Used : <b>" & User.Identity.AuthenticationType & "</b>"
  Else
    displayCredentials.InnerHtml = "Sorry, you have not been authenticated."
  End If
End Sub

Thanks very much for your help.
0
 
DanBAtkinsonAuthor Commented:
I have awarded 400 points for the login.aspx code and 100 points for the web.config file. Both are to davidlars99 for his excellent contribution.

Points are also split so that people can see easily what the points were for.
0
 
davidlars99Commented:
I'm glad you got it up and running, however I'm sorry to be so slow as I said it's my ugly schedule not me...   :)
0
 
DanBAtkinsonAuthor Commented:
hehe! No worries. That sub actually worked as well (except some ';' error) so it's all good!

Thanks a lot!!!

Happy Easter!
0
 
davidlars99Commented:
same to you  :)
0

Featured Post

Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

  • 29
  • 18
Tackle projects and never again get stuck behind a technical roadblock.
Join Now