Click here to Skip to main content
15,885,890 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm new in asp.net and I have a problem. in my asp.net webdirectory I have some pages for users and an Admin Folder for administrator , I want to use some tags like authentication & authorization in my web.config File to determine my administrator username and password and determine only the admin can use pages in the admin folder but my problem is I did'nt use any login control in my web for my users to sign in.I use some textboxes which give the users information and then I connect to my table in database and check their information and I want to know how can I do that with this condition? I'll become so thankfull if any body help me. users Sign in with thier emails and passwords this is my code:

XML
<tr>
        <td>
            &nbsp;Email :
        </td>
        <td class="style1">
            &nbsp;<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <br />

        </td>

    </tr>
     <tr>
        <td>
            &nbsp;
        </td>
        <td class="style1">
            &nbsp; <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                ErrorMessage="please enter your email!"
                ControlToValidate="TextBox1"
                Display="Dynamic" ForeColor="#CC0000" ValidationGroup="SignIn"></asp:RequiredFieldValidator>
            <br />
            <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="incorrect format!" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"  Display="Dynamic"  ForeColor="#CC0000" ControlToValidate="TextBox1" ValidationGroup="SignIn"></asp:RegularExpressionValidator>
           <br />

        </td>

    </tr>
    <tr>
        <td>
            &nbsp;password:
        </td>
        <td class="style1">
            &nbsp;<asp:TextBox ID="TextBox2" runat="server" TextMode="Password" ></asp:TextBox>
           <br />
        </td>

    </tr>
     <tr>
        <td>
            &nbsp;
        </td>
        <td class="style1">
         &nbsp;
            <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Enter your password" ControlToValidate="TextBox2"  Display="Dynamic" ForeColor="#CC0000" ValidationGroup="SignIn" ></asp:RequiredFieldValidator>

        </td>

    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
        <td class="style1">
            &nbsp;<asp:Button ID="Button2" runat="server" Text="enter"
                Width="123px" onclick="Button2_Click" ValidationGroup="SignIn" />
        </td>

 protected void Button2_click(object sender, EventArgs e)
{
  if (Membership.ValidateUser(TextBox1.Text.Trim(), TextBox2.Text.Trim()))
 {
     if (Roles.IsUserInRole(TextBox1.Text.Trim(), "Admin"))
     {
         Response.Redirect("Admin/Default.aspx");
         Session["user"] = "admin";
     }
    // ad.Text = "admin";
 }
 else
 {
   int c = -1;
 SqlConnection cn2 = new SqlConnection();
 cn2.ConnectionString = "server = . ; database = mobile_store ; Trusted_Connection=true";
 DataTable tb = new  DataTable();

 SqlCommand cmd2 = new SqlCommand();
 cmd2.Connection = cn2;
 cmd2.CommandType = CommandType.StoredProcedure;
 cmd2.CommandText = "Check_Email_Pass";
 cmd2.Parameters.AddWithValue("@mail", TextBox1.Text.Trim());
 cmd2.Parameters.AddWithValue("@pass", TextBox2.Text.Trim());
 cmd2.Parameters.Add("@res", SqlDbType.Int);
 cmd2.Parameters["@res"].Direction = ParameterDirection.Output;

 SqlDataAdapter da = new SqlDataAdapter(cmd2);
 da.Fill(tb);
 try
 {
     cn2.Open();
     cmd2.ExecuteNonQuery();
     c = Convert.ToInt32(cmd2.Parameters["@res"].Value);

     switch (c)
     {
         case 1:
             {

                 Session["user"] = tb.Rows[0][0].ToString() + " " + tb.Rows[0][1].ToString();
                 Session["authenticate"] = true;
                 Session["id"] = Convert.ToInt32( tb.Rows[0][2]);

                 ((MasterPage)this.Master).lable2Visible = Session["user"].ToString();
                 Label2.Text = "Welcome" + " " + tb.Rows[0][0].ToString() + " " + tb.Rows[0][1].ToString();
                 TextBox1.Text = null;
                 if (Session["pagesource"] != null)
                 {
                     Response.Redirect((string)Session["pagesource"]);
                 }
                 else
                 {
                     Response.Redirect("~/user_page.aspx");
                 }

             }
             break;
         case 0:
             {
                 Label2.Text = "your password is wrong";

             }
             break;
         case 2:
             {

                 Label2.Text = "this email has registered before <br/> please sign up first";
                 TextBox3.Text = TextBox1.Text.Trim();
             }
             break;
         default:
             break;
     }


 }

 catch (Exception ex)
 {
     Label1.Text = ex.ToString();

 }
 finally { cn2.Close(); }
}
}


in my we.config file:

XML
<system.Web>
    <authentication mode="Forms">
        <forms  timeout="20" slidingExpiration="true" cookieless="AutoDetect" protection="All" requireSSL="false" enableCrossAppRedirects="false"  >
            <credentials passwordFormat="Clear">
                <user name="elmiragolshanff@yahoo.com" password="elmira" />
            </credentials>
        </forms>
    </authentication>
    </system.web>


        <location path="Admin">
    <system.web>
        <authorization>
            <allow users="elmiragolshanff@yahoo.com" roles="Admin" />
        </authorization>

</location>

    </system.web>
Posted
Updated 2-Jan-13 23:38pm
v3

 
Share this answer
 
Comments
elmirag 3-Jan-13 11:30am    
Thanks for your reply I looked at that link and I think it is so use full but I have edited my code and I want to know why it does not work .can you tell me?thank you
Adam R Harris 3-Jan-13 15:08pm    
I can take a look at it later and see but i'm pretty swamped at work right now so it wont be until later this evening.
elmirag 4-Jan-13 15:28pm    
I wll becom grateful if you help me when you have time
Adam R Harris 4-Jan-13 16:41pm    
I haven't forgotten about you, just got real busy with work.
Can you give me a few more details regarding exactly what isn't working and also take a look at RedirectFromLoginPage (http://msdn.microsoft.com/en-us/library/ka5ffkce.aspx)
elmirag 5-Jan-13 9:46am    
I have a credentials tag in my web.config and I declare my admins username and password in this tag and I use Membership.ValidateUser(TextBox1.Text.Trim(), TextBox2.Text.Trim()).ToString()in my button_onclick event in my asp page to Distinguish whether the user is the admin or not but it always return false
I changed it.now It works fine
web.configfile:
XML
<authentication mode="Forms">
            <forms  timeout="30" loginUrl="~/entrance_before_paying.aspx" defaultUrl="Admin/Default.aspx" name=".ASPXFORMSDEMO"  cookieless="AutoDetect" protection="All"   >
            
            <credentials passwordFormat="Clear">
                    <user name="elmiragolshanff@yahoo.com"  password="elmira" />
                </credentials>
            </forms>
        </authentication>

my on button_click event in entrance_before_paying.aspx page :


C#
if (FormsAuthentication.Authenticate(TextBox1.Text.Trim(), TextBox2.Text.Trim()))
       {

               Response.Redirect("Admin/Default.aspx");
                Session["user"] = "admin";     

       }
else{ //I wrote the code to authenticate users ....}
 
Share this answer
 
v3
Comments
Adam R Harris 8-Jan-13 10:17am    
Hey, really glad you got it figured out. Also I feel bad for leaving you waiting my assistance but i'm sure you know that pesky life always gets in the way.

Your code looks good with one little exception, you should really look at using RedirectFromLoginPage (http://msdn.microsoft.com/en-us/library/ka5ffkce.aspx) to send the user back to the page they requested or back to the default page. It's a small thing but its what users have come to expect and i'm sure you will be tasked with making that work at one point or another so you might as well get ahead of the game.
elmirag 15-Jan-13 6:12am    
can I change the username and password which are stored in my credential tag at run time.I mean can I make a page with a form in it for my admin where he can change his username and password?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900