FormsAuthentication Login

Hi,

I created a 3-tier ASP.NET web app

How do i code a login.aspx for login authentication
and if they go to other pages, they will be redirected to
login.aspx to login..

Once they are logged in, they can return to the last page they were at.

What do i add in web.config and login.aspx
jedistarAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
SandeepRRConnect With a Mentor Commented:
U have to add reference to
using System.Security.Cryptography;

----------
SHA1 sha1 = SHA1.Create();
byte [] password = sha1.ComputeHash(Encoding.Unicode.GetBytes(txtPassword.Text));
---------------
this will generate the byte array of the password.

while registering the user pass the password array to the database and the column type will be "byte"

and while checking for the user login select the password field from the database by passing the username in query,

and then again encypt the password entered by user and compair it with the password u are getting from the select query.

as i emntioned the Sha1 has only encryption.

------------------------------Adding user to database---------------------
cn.ConnectionString = "Connection string";
                  SqlCommand  cmd = new SqlCommand();

                  cmd.CommandText = "Insert into UserInfo1 values (@UserName, @Password)";
                  cmd.Connection = cn;

                  cmd.Parameters.Add("@UserName", SqlDbType.VarChar, 50,"UserName");
 
                  cmd.Parameters.Add("@Password", SqlDbType.Binary, 50, "Password");

            
                  SHA1 sha1 = SHA1.Create();
                  byte [] password = sha1.ComputeHash(Encoding.Unicode.GetBytes(txtPassword.Text));
                  cmd.Parameters["@UserName"].Value  = txtName.Text;
                  cmd.Parameters["@Password"].Value  = password;
                  
                  cn.Open();
                  cmd.ExecuteNonQuery();
                  cn.Close();
--------------------------------------------------------------------------


----------------------Checking the login status============
      cn.ConnectionString = "Connection string";
                  SqlCommand cmd = new SqlCommand();
                  cmd.Connection  = cn;
cmd.CommandText = "SELECT * FROM UserInfo1 WHERE (UserName = @UserName and Password = @Password)";


                  cmd.Parameters.Add("@UserName", SqlDbType.VarChar, 50,"UserName");

                  cmd.Parameters.Add("@Password", SqlDbType.Binary, 50, "Password");

            
                  SHA1 sha1 = SHA1.Create();
                  byte [] password = sha1.ComputeHash(Encoding.Unicode.GetBytes(txtPassword.Text));
                  cmd.Parameters["@UserName"].Value  = txtName.Text;
                  cmd.Parameters["@Password"].Value  = password;
      cn.Open();
                        if (dr.Read())
                  {
//                            login succesul
                  }
                  else
                  {
//                                                          login failed
                        }
---------------------

Regards
SandeepRR
0
 
TorrwinCommented:
Check out this PAQ where I answered basically the same question:
http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/ASP_DOT_NET/Q_21386152.html

Let me know if you need any help,
-Torrwin
0
 
jedistarAuthor Commented:
the web.config is done.

I need to know how do i code my login.aspx to check for username
and what do i do to give it credientials?

(BTW, why do you encrpyt the ticket)
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
TorrwinCommented:
Step 5 shows the code for the login page.  

You encrypt it so that when it's stored locally in a cookie the data is secure.
0
 
jedistarAuthor Commented:
That is based on LDAP isnt it?
my userpass is in my MS SQL server
0
 
SandeepRRCommented:
Hi jedistar,
             As ur Users credentials are stored in the SQL
You can do one thing write the query which passes the username and password to select query. and perform the ExececuteScalar  method of the command object.
If it returns nonzero then the user is authenticated else he/she is not authenticated..


And regarding the encripting the password you can do one thing,
you store the password for the user in the databse in byte format(i.e using Byte datatype for the table column) and use Sha1 algorithn to encript the password when user register to user system.

Now as the Sha1 is for encripting only,
so while passing the password to database for comaprisioon u can encript and send to database. Also the same password u can store in cookie without any harm as it will be in encripted form.


Regards
SandeepRR
0
 
jedistarAuthor Commented:
any samples?
0
 
jedistarAuthor Commented:
How do we convert this to stored procedures?
0
 
jedistarAuthor Commented:
i.e "SELECT * FROM UserInfo1 WHERE (UserName = @UserName and Password = @Password)";
0
 
SandeepRRCommented:
You can create the SP and add following code in that

Create PROCEDURE InsertUser
    @UserName varchar(20), @Password byte(50)
AS

SELECT * from UserInfo1 WHERE (UserName = @UserName and Password = @Password)
GO


Regards
SandeepRR
0
 
jedistarAuthor Commented:
How abt INSERTING USER if the email address of the user already exist, it should not be added.
How do i do that?

Also will it throw an exception if an email address exists?
0
 
SandeepRRCommented:
No for this u can go two way
one is u run a seperate query validating the email ID first prior to insertion

and second u run the insertion commmand and track the "Violation of PRIMARY KEY constraint " exception and take the action depending on that..


But as per me, you should go for the first way,


and for the validation of email id u can right the select query with the where clause as (UserName = @UserName ) and check with reader if it is returning any rows or not

if the no of rows is one then the user is already exists and u can promt user in that way,
or u can go and run the insertion query if no. of rows returned by reader is 0.


Regards
SandeepRR
0
 
jedistarAuthor Commented:
ok how does a stored procedure for INSERT looks like
that checks if the @email exists already
0
 
SandeepRRCommented:
the insert SP will be the same but as i told you, u have to track the SQLException for Duplicate entry if u dont have to go for two SPs,
else you can create two SPs, one for emailID varificationa and other for insertion.(Recommended)
0
 
jedistarAuthor Commented:
Yeah my qn was what do i type to prevent duplicates
0
 
jedistarAuthor Commented:
Hi Sandeep, I better not stray off topic, back to my initial question..

I do know how to check with the database if the username password matches.. now how do i give it
formsauthentication creditials?

In your code you wrote:
//                         login successful

This is the part i need.. How do i give the user credentials so that next time
he goes to a secure location governed by web.config's <authentication mode="forms">
he can see the page and won't be redirected to re-login.

know what i mean? thanks.
0
 
jedistarAuthor Commented:
What should i put in

//                         login successful


and


//                         login failed

i.e forms.authenticate.user?
0
 
jedistarAuthor Commented:
(Question raised to 500)
0
 
SandeepRRCommented:
Hi

For login succesful u have to create the FormsAuthenticationTicket and add that to the HttpCookie,
and do some additional operation that are given below

---------------------Login Succesful code-----------------------
FormsAuthenticationTicket Ticket= new FormsAuthenticationTicket( 1 ,(string)Session["EmpId"],DateTime.Now,DateTime.Now.AddMinutes(30),false,(string)Session["RoleName"],FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(Ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
      if (Ticket.IsPersistent)
      {
            cookie.Expires=Ticket.Expiration;
      }

      Response.Cookies.Add(cookie);
      string returnUrl = Request.QueryString["ReturnUrl"];
      if (returnUrl == null || returnUrl.Length==0)
      returnUrl = "default.aspx";//this is default  page of the application which will u show after succesful login
      Response.Redirect(returnUrl);


And user froma authentication tag in WEB.CONFIG will be like this

<authentication mode="Forms">
      <forms name=".ADUAUTH" loginUrl="logon.aspx" requireSSL="true" protection="All" path="/" timeout="30">
      </forms>
    </authentication>

amd in web.config set
cookieless="false"
in sessionState tag

Regards
SandeepRR
0
 
SandeepRRCommented:
And in the code i am usig the users roles too that i cam aading as the userdata in the FormsAuthenticationTicket, that u have to sort out  as per ur requirment.

0
 
jedistarAuthor Commented:
Thanks, whats the difference between the above whole code

vs just

FormsAuthentication.RedirectFromLoginPage(user, true);
0
 
SandeepRRCommented:
the diffenrce in my code is that, in my code i am encripting all the infrmation and then storing it in the cookie
0
 
jedistarAuthor Commented:
I used your code and even with the right username and password, or i even tested it by putting your
code in page load of \secure\details.aspx

it still redirects me to login.aspx

web.config:
    <authentication mode="Forms">
            <forms loginUrl="login.aspx" protection="All" timeout="20" />
    </authentication>

     <authorization>
        <deny users="?"/>
    </authorization>

any idea?
0
 
SandeepRRCommented:
Hi jedistar,
            The code that have given u is for the login page, that u have to write on the click event of the login button

addition to that u have to write the code that checks whether the user is authenticated or not

i.e u have to call the select command that checkes the user id and password
and as i told u if u have using Sha1 for password encription while registring the user, u have to write SP accordingly(i.e. passing the encripted password entered by user in the select statement)

and write the code for forms authentication(i.e. for creating cookie and all)if the user is authenticated. else show the "Incorrect UserName or Password Error" to User

Regards
SandeepRR
0
 
jedistarAuthor Commented:
Sandeep i have done so, but the page still directs me to login page.
how?
0
 
jedistarAuthor Commented:
Please help.
0
 
SandeepRRCommented:
Hi Jedistar

Actually that code is working and and i dont know why it is not working in ur senerio

http://support.microsoft.com/default.aspx?scid=kb;EN-US;308157

this URL contain the same steps explaining how to implement the Forms Authentication,,

u can can try that out,

SandeepRR
0
All Courses

From novice to tech pro — start learning today.