How to use ASP.NET's form authentication?

Here is my login form:

<form method="post" action="user.aspx" id="userForm" runat="server">
        <section id="login" class="tab">
            <label>Email<span class="red">*</span></label>
            <asp:TextBox id="loginEmail" value="" class="form-text" runat="server" />
            <label>Password<span class="red">*</span></label>
            <asp:TextBox id="loginPassword" value="" class="form-text" runat="server" />
            <br />
            <asp:Button text="Log In" class="form-submit" runat="server" OnClick="LogIn" />
        </section>

Open in new window


Here is the method that authenticates it:

        protected void LogIn(object send, EventArgs e)
        {

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                con.Open();
                hashPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(loginPassword.Text.Trim(), "sha1");

                // build the sql query
                query = "SELECT id, FirstName FROM Users WHERE Email = @email AND Password = @hashPassword";

                // create the command object
                SqlCommand cmd = new SqlCommand(query, con);
                // parameters to protect from sql injection
                cmd.Parameters.AddWithValue("@email", loginEmail.Text.Trim());
                cmd.Parameters.AddWithValue("@hashPassword", hashPassword);
                // execute the query
                SqlDataReader dr = cmd.ExecuteReader();
                Response.Write(string.Format("<script type='text/javascript'>alert('{0}');</script>", hashPassword));

                // When using datareader.read(), each time you call that it moves forward in the records returned by one record. 
                // If you only had one record returned then the model you are using will skip over it and will be returning 0 rows
                if (dr.HasRows)
                {
                    Response.Write(string.Format("<script type='text/javascript'>alert('hi');</script>"));
                    while (dr.Read())
                    {
                        // store the user's id and name into session variables
                        Session["id"] = dr["id"];
                        Session["name"] = dr["FirstName"];
                        //string id = Session["id"].ToString();
                        //string name = Session["name"].ToString();
                    }
                    completion succeeded = new completion("Login credentials verified.");
                    succeeded.message(this.success);
                    GlobalContent LoginStatus = new GlobalContent();
                    LoginStatus.Welcome();
                }
                else
                {
                    errors failHeader = new errors("Error:");
                    errors fail = new errors("The username or password you entered was incorrect.<br />Please make sure your caps lock key is off and try again.");
                    failHeader.message(this.error);
                    fail.message(this.error);
                }
            } // end using SqlConnection
        } // end LogIn method

Open in new window


But where would I use something like FormsAuthentication.RedirectFromLoginPage or FormsAuthentication.SignOut()? Are these functions that I need to create? I need some help getting ASP.NET's form authentication stuff to click!
FairyBusinessAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Manoj PatilSr. Software EngineerCommented:
Hi Check this tutorial

ASP.NET Form Authentication

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
mrRanyCommented:
Just wanted to recommend to learn a little more about Linq to SQL. Awesome thing lets you act with db table like a class and call stored procedure like a method. I guess you will love it.
FairyBusinessAuthor Commented:
@techChallenger1 thanks for the tutorial

@mrRany you gave me a link in another language lol but I'm sure I would love it :)
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

mrRanyCommented:
FairyBusiness,
yeah, that's my one, you are right.. Sorry for that and please let me correct it.
Here it is.
FairyBusinessAuthor Commented:
@techChallenger1 yeah this tutorial is way to confusing for me and it has so much going on. For example I have no idea what this means or how to use this:

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

Open in new window


They briefly explain it but its not enough for me to even begin to know what to do with it or how to make it work.

Then in this part Create a Sample Database Table to Store Users Details
I have no idea why I'm creating a table or dropping it. I don't get whats going.

This part makes the most since to me Code the Event Handler So That It Validates the User Credentials  but there are still parts that don't make a lot of since to me like this line:

System.Diagnostics.Trace

Open in new window


So basically there is just too much at this point I'm not familiar with enough of C#/ASP.NET to make this work.  Is there a more simple way to accomplish this?
mrRanyCommented:
allow
A question mark (?) allows anonymous users; an asterisk (*) allows all users.

deny
A question mark (?) denies anonymous users and an asterisk (*) indicates that all users are denied access.
Manoj PatilSr. Software EngineerCommented:
Hi
The code u confused with, is need to add in web.config file

And as mrRany explained you is correct

asterisk (*) represents all users and the question mark (?) represents anonymous users

Manoj PatilSr. Software EngineerCommented:
You may like this Step by Step tutorial

http://msdn.microsoft.com/en-us/library/ff649314.aspx
FairyBusinessAuthor Commented:
yeah I got that from the tutorial but I still don't what its used for or with. Just standing alone by itself it doesn't do anything.  That's the problem just bc I "know" how something works, doesn't mean I get how to use it or how it connects to anything else.

Do you know of a more simple way to use ASP.NET form's authentication? This tutorial is too much for me. . .
mrRanyCommented:
FairyBusiness,
please don't panic ^_^ everything is coming step by step even little ones.

May be you wish to make your own step by step manual here?
FairyBusinessAuthor Commented:
hmm maybe :)
Ok, you see what code I have above (in my question).

And I added this to my web.config file:

		<authentication mode="Forms">
      <forms name=".ASPXFORMSDEMO" loginUrl="user.aspx" protection="All" path="/" timeout="30" />
		</authentication>
    <authorization>
      <deny users ="?" />
      <allow users = "*" />
    </authorization>

Open in new window


So what would be the next small step??
Manoj PatilSr. Software EngineerCommented:
Finally Got the Required Document for your perfect clarification. Really Good

ASP.Net Form Authentication - Best Practices for Software Developers

mrRanyCommented:
Make sure you've added this code inside configuration inside system.web section.

Add user.asxp file to your project and insert log-in functionality.
mrRanyCommented:
techChallenger1,
good one but still not for a beginner I think
FairyBusinessAuthor Commented:
@techChallenger1 ok I'll have to get thru this tutorial and see where I'm at

@mrRany yep its inside of the system.web

you say:

Add user.asxp file to your project and insert log-in functionality.

Its already in my website, but what do you mean by insert log-in functionality? I have a LogIn function (see my question at the top)
mrRanyCommented:
Now add to web.config inside configuration section:
<location path="user.asxp">
        <system.web>
            <authorization>
                <allow users="*"/>
            </authorization>
        </system.web>
    </location>

Open in new window

to allow this page be opened by everyone.

If you have a folder for (example) images and they are in use by user.asp then add that folder as well
<location path="images">
		<system.web>
			<authorization>
				<allow users="*"/>
			</authorization>
		</system.web>
	</location>

Open in new window

FairyBusinessAuthor Commented:
I have a user.aspx.cs file that user.aspx uses.

I tried adding the location tabs but got an error:


error.png
FairyBusinessAuthor Commented:
*tags
mrRanyCommented:
Follow me : )
Inside <configuration>, not inside <system.web>.

</system.web>
<location>

Open in new window

FairyBusinessAuthor Commented:
ok we're good on that now. next step?
mrRanyCommented:
Please let me see your method (Button_Click) on user.aspx.
FairyBusinessAuthor Commented:
<asp:Button text="Log In" class="form-submit" runat="server" OnClick="LogIn" />

Open in new window

mrRanyCommented:
I mean code of LogIn on server side.
FairyBusinessAuthor Commented:
protected void LogIn(object send, EventArgs e)
{

    using (SqlConnection con = new SqlConnection(connectionString))
    {
        con.Open();
        hashPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(loginPassword.Text.Trim(), "sha1");

        // build the sql query
        query = "SELECT id, FirstName FROM Users WHERE Email = @email AND Password = @hashPassword";

        // create the command object
        SqlCommand cmd = new SqlCommand(query, con);
        // parameters to protect from sql injection
        cmd.Parameters.AddWithValue("@email", loginEmail.Text.Trim());
        cmd.Parameters.AddWithValue("@hashPassword", hashPassword);
        // execute the query
        SqlDataReader dr = cmd.ExecuteReader();
        Response.Write(string.Format("<script type='text/javascript'>alert('{0}');</script>", hashPassword));

        // When using datareader.read(), each time you call that it moves forward in the records returned by one record. 
        // If you only had one record returned then the model you are using will skip over it and will be returning 0 rows
        if (dr.HasRows)
        {
            Response.Write(string.Format("<script type='text/javascript'>alert('hi');</script>"));
            while (dr.Read())
            {
                // store the user's id and name into session variables
                Session["id"] = dr["id"];
                Session["name"] = dr["FirstName"];
                //string id = Session["id"].ToString();
                //string name = Session["name"].ToString();
            }
            completion succeeded = new completion("Login credentials verified.");
            succeeded.message(this.success);
            GlobalContent LoginStatus = new GlobalContent();
            LoginStatus.Welcome();
        }
        else
        {
            errors failHeader = new errors("Error:");
            errors fail = new errors("The username or password you entered was incorrect.<br />Please make sure your caps lock key is off and try again.");
            failHeader.message(this.error);
            fail.message(this.error);
        }
    } // end using SqlConnection
} // end LogIn method

Open in new window

FairyBusinessAuthor Commented:
Its also in my question above (probably easier to read too)
mrRanyCommented:
Let's make something like

//...
using System.Web.Security;
//... 
// username and password - I mean your fields on client side (possible you are using other name)
protected void LogIn(object send, EventArgs e)
{
  if (username.Text.Trim() == "user" && password.Text.Trim() == "password") {
    Session["name"] = "user";
    FormsAuthentication.RedirectFromLoginPage(name, false);
 }
}

Open in new window

mrRanyCommented:
FormsAuthentication.RedirectFromLoginPage("user", false);

Open in new window

FairyBusinessAuthor Commented:
I'm not quite sure whats going on in this part.  How did you my LogIn function become so reduced? It doesn't have most of the stuff that I had it in. . . how does it still operate the same?  There would be nothing to check the username or password against because that information is retrieved from my database later in my function.

What does this mean/do exactly?
FormsAuthentication.RedirectFromLoginPage("user", false);

Open in new window

mrRanyCommented:
I just want to show you in a simple way how FormAuthentication works.
You will add all DB stuff after that. Think that only username as "user" and password as "password" must only be accepted.
FormsAuthentication.RedirectFromLoginPage will redirect your request to a page that you've requested before. If you don't specify a page then it will be redirected to FormsAuthentication.DefaultUrl.
FairyBusinessAuthor Commented:
ok, is that it to the form authentication stuff? anything else I need to know?

I just put this at the end of my LogIn function?
FormsAuthentication.RedirectFromLoginPage("user", false);

Open in new window

FairyBusinessAuthor Commented:
Do I call this function on any page that is supposed to have logged in only users?
mrRanyCommented:
There are so many things you need to know but not in a time of headache for sure.
May be that's enough for today? Too much information won't be useful i think.

Now just run your application on your local machine and try to open default.aspx (for instance);
You will be redirected to user.aspx page and only after successful authentication your browser will be redirected to default.aspx.
mrRanyCommented:
Call this function only after all required checks on logIn page if success.
FairyBusinessAuthor Commented:
But I don't want to force my users to login or create an account if they don't want. So this will prevent users from viewing any page till they login?
FairyBusinessAuthor Commented:
Eh, my headaches starting to get better actually :)
mrRanyCommented:
Then move all pages that you want to hide from anonymous into some folder and set deny="?" on it.
Location can be set for a file and for a folder.
FairyBusinessAuthor Commented:
Ok, so say I start to create pages that are for logged in users only, I put those in a folder. How do I set the folder to deny="?"

  <location path="user.asxp">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>

Open in new window

FairyBusinessAuthor Commented:
How about this?

<location path="LoggedIn">
    <system.web>
      <authorization>
        <allow users="Admin,Clients"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>

Open in new window


How would they know who the "users" are? And where do I set the values for Admin and Clients?
mrRanyCommented:
Keep reading..
FairyBusinessAuthor Commented:
Ok, I think its good now. Thanks!
mrRanyCommented:
By the way, you don't need to keep a user name in Session because you always can get it from Context.User.Identity.Name.
FairyBusinessAuthor Commented:
so Session["name"] is the same as Context.User.Identity.Name
mrRanyCommented:
No they are different objects but User.Identity.Name gets its value automatically after authorization; Session you have to control by yourself.
mrRanyCommented:
In order to check if user logged in you use Context.User.Identity.IsAuthenticated.
FairyBusinessAuthor Commented:
ok so

if (!string.IsNullOrEmpty(Session["name"] as string))

is the same as

if (!string.IsNullOrEmpty(Context.User.Identity.IsAuthenticated))

to see if a user is logged in?
mrRanyCommented:
Context.User.Identity.IsAuthenticated has return type bool (true or false) so you can add just
if (!Context.User.Identity.IsAuthenticated)

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.