Login control FAQ :

Rate It (4)

Last post 12-17-2009 7:42 AM by jasbir_maan06. 23 replies.

Sort Posts:

  • Login control FAQ :

    03-27-2009, 12:31 PM
    • All-Star
      60,921 point All-Star
    • anas
    • Member since 09-21-2006, 8:31 AM
    • Palestinian Territory, Occupied
    • Posts 6,865
    • Moderator

    This post contains some of the most asked questions when using login control.

    1- how to redirect users to different pages based on their roles.

    This can be done by handling the LoggedIn event of the Login control. 

    protected void Login1_LoggedIn(object sender, EventArgs e)    {
    // if there is no returnUrl in the query string , we redirect based on user role
    if (string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
    {
    // please don't use User.IsInRole here , because it will not be populated yet at this stage.
    if (Roles.IsUserInRole(Login1.UserName, "Admins"))
    Response.Redirect("~/Admins/Default.aspx");
    else if (Roles.IsUserInRole(Login1.UserName, "Editors"))
    Response.Redirect("~/Editors/Default.aspx");
    }
    }
    2- how to hide the login control from the logged in users ?

    To hide the login control for the logged in users , set it’s VisibleWhenLoggedIn property to false.

    <asp:Login ID="Login1" runat="server" VisibleWhenLoggedIn="False" …

    You can also use the LoginView control to accomplish that :

        <asp:LoginView ID="LoginView1" runat="server">
    <AnonymousTemplate>
    <asp:Login ID="Login1" runat="server">
    </asp:Login>
    </AnonymousTemplate>
    </asp:LoginView>
     
    3-How to hide “remember me next time” checkbox ?

    You may need to prevent the users from checking “remember me next time” checkbox to prevent crating a persistent authentication cookie.

    To do that , you just need to set it’s DisplayRememberMe property to “false” and then you need to set it’s RememberMeSet property.

    If you want to force the website to remember the users , you set the RememberMeSet property to true, else you set it to false.

    <asp:Login ID="Login1" runat="server" DisplayRememberMe="false" RememberMeSet="false" …


    4-How to use the login control with my existing users table ?

    By default,Login control will use the membership provider to validate users credentials , but if you already have your custom users table , you can use the login control like this :

    protected void  Login1_Authenticate(object sender, System.Web.UI.WebControls.AuthenticateEventArgs e)
    {
    string userName = Login1.UserName;
    string password = Login1.Password;

    bool result = UserLogin(userName, password);
    if ((result))
    {
    e.Authenticated = true;
    }
    else
    {
    e.Authenticated = false;
    }
    }

    private bool UserLogin(string userName, string password)
    {

    // read the coonection string from web.config
    string conString = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;

    using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(conString))
    {
    //' declare the command that will be used to execute the select statement
    SqlCommand com = new SqlCommand("SELECT UserName FROM Users WHERE UserName = @UserName AND Password = @Password", con);

    // set the username and password parameters
    com.Parameters.Add("@UserName", SqlDbType.NVarChar).Value = userName;
    com.Parameters.Add("@Password", SqlDbType.NVarChar).Value = password;

    //' execute the select command
    try
    {
    con.Open();
    //' execute the select statment
    string result =Convert.ToString( com.ExecuteScalar());
    //' check the result
    if (string.IsNullOrEmpty(result))
    {
    //invalid user/password , return flase
    return false;
    }
    else
    {
    // else return true , valid login
    return true;
    }
    }
    catch (Exception ex)
    {
    throw;
    }
    }
    }
      

    5-I don’t want the login control to render as html table , instead i want it to render as div , how to do that ?

    You can use the CSS friendly control adapters , check this link.


    6- I’m getting invalid login after i published my website , the user name and password was working locally , what’s the problem ?

    One possible reason is the applicationName in membership configuration, check this link for more information .

    7-After i published my website , I’m getting System.Web.Security.SqlMembershipProvider' requires a database schema compatible with schema version '1'  .. error ,what to do ?

    One possible reason is that the published version of  "aspnet_SchemaVersions" table doesn't have the correct values , please make sure that it have the values like below :

    Feature CompatibleSchemaVersion 
    IsCurrentVersion
    common 1 TRUE
    health monitoring 1 TRUE
    membership 1 TRUE
    personalization 1 TRUE
    profile 1 TRUE
    role manager 1 TRUE


    8-How to display the login in popup ?

    http://weblogs.asp.net/lkempe/archive/2007/01/28/login-control-in-an-asp-net-ajax-toolkit-popupcontrolextender-with-a-close-button.aspx

    9- How can i log the invalid login attempts ?

    You can handle the LoginError event of the login control :

        protected void Login1_LoginError(object sender, EventArgs e)
    {
    // here you can login the invalid attempts
    string UserName = Login1.UserName;
    string Password = Login1.Password;
    // log the attempt

    }

    10-I' specified my website users in the credential section in web.config , can i still use the login control ?

    Yes you can , you just need to handle the login control authenticate event .

    Assume you have this Credential section in web.config :

    <authentication mode="Forms">
    <forms>
    <credentials passwordFormat="Clear">
    <user name="User1" password="****" />
    <user name="User2" password="****" />
    </credentials>
    </forms>
    </authentication>

    You can let the login control use the mentioned section like this :

        protected void Login1_Authenticate(object sender, System.Web.UI.WebControls.AuthenticateEventArgs e)
    {
    string UserName = Login1.UserName;
    string Password = Login1.Password;

    if (FormsAuthentication.Authenticate(UserName, Password))
    {
    e.Authenticated = true;
    }
    else
    {
    e.Authenticated = false;
    }
    }

    The FormsAuthentication.Authenticate method will automatically check users against the credential section.

    11- I'm not using FormsAuthenticaiton, instead I'm using the session object to secure my website , can i still use the login control ?

    Yes , you can use it , please read my post about this.

     

    Hope it helps.

    Regards,

    Anas Ghanem | Blog

  • Re: Login control FAQ :

    03-27-2009, 4:33 PM
    • All-Star
      36,899 point All-Star
    • rtpHarry
    • Member since 10-01-2006, 12:51 PM
    • Lincoln, England
    • Posts 5,953

     Hey,

    Great tips Anas, I have learned a few things in this post!

    I just wanted to add a couple of notes:

    4-How to use the login control with my existing users table ?

    You could also create a custom membership provider so that this works seamlessly with your login control:


    5-I don’t want the login control to render as html table , instead i want it to render as div , how to do that ?

    You can also take control over the markup of your Login control by clicking the smart tag (the arrow in the top right of the control when viewed in Design View) and click Convert To Template.

    This will expand all the code so you can style it up however you like.

     

     

  • Re: Login control FAQ :

    03-27-2009, 4:52 PM
    • All-Star
      60,921 point All-Star
    • anas
    • Member since 09-21-2006, 8:31 AM
    • Palestinian Territory, Occupied
    • Posts 6,865
    • Moderator

    Hi,

    rtpHarry:

    4-How to use the login control with my existing users table ?

    You could also create a custom membership provider so that this works seamlessly with your login control:

    Sure, that's another solution for working with custom tables.If you followed this way,there is no need to customize or write any code for the Login control , the control must work natively with no problems.

    rtpHarry:

    5-I don’t want the login control to render as html table , instead i want it to render as div , how to do that ?

    You can also take control over the markup of your Login control by clicking the smart tag (the arrow in the top right of the control when viewed in Design View) and click Convert To Template.

    This will expand all the code so you can style it up however you like.

    The login control always create a table to wrap it's contents , so even you customized it's layout and used <div> , the control will add outer html table to the rendered markup.

    Thanks

    Regards,

    Anas Ghanem | Blog

  • Re: Login control FAQ :

    03-27-2009, 6:16 PM
    • All-Star
      36,899 point All-Star
    • rtpHarry
    • Member since 10-01-2006, 12:51 PM
    • Lincoln, England
    • Posts 5,953

    anas:

    rtpHarry:

    5-I don’t want the login control to render as html table , instead i want it to render as div , how to do that ?

    You can also take control over the markup of your Login control by clicking the smart tag (the arrow in the top right of the control when viewed in Design View) and click Convert To Template.

    This will expand all the code so you can style it up however you like.

    The login control always create a table to wrap it's contents , so even you customized it's layout and used <div> , the control will add outer html table to the rendered markup.



    Good point!
  • Re: Login control FAQ :

    05-16-2009, 3:21 AM
    • Member
      409 point Member
    • khparhami
    • Member since 04-09-2009, 5:19 AM
    • Tehran
    • Posts 189

    Thanks, It was a great help. I have an extra question:

    What database is used for storing the usernames and passwords and other datas and how can I use it for example to show the list of users? and can I change the database into my own?

    Best regards
    Khashayar

    ---------------------------------------------
    Please: Don't forget to click "Mark as Answer" on the post that helped you. That way future readers will know which post solved your issue.
  • Re: Login control FAQ :

    05-19-2009, 6:56 PM
    • All-Star
      36,899 point All-Star
    • rtpHarry
    • Member since 10-01-2006, 12:51 PM
    • Lincoln, England
    • Posts 5,953

    khparhami:
    What database is used for storing the usernames and passwords and other datas and how can I use it for example to show the list of users?
     

    By default it uses the built in asp.net membership, roles, authentication, authorisation technologies.

    khparhami:
    can I change the database into my own?


    Yeah you can write your own providers which plugin to the standard api and then let you use your own database

  • Re: Login control FAQ :

    05-22-2009, 3:33 PM
    • All-Star
      63,185 point All-Star
    • TATWORTH
    • Member since 02-04-2003, 1:34 PM
    • England
    • Posts 12,333
    • TrustedFriends-MVPs

     Anas

      Excellent article! Is there a way of switching a site based upon a database setting so that only administrators can access a given site?

    [Edit: I suppose that if accounts can be programmatically diabled and re-enabled, I could just switch the non-admin accounts on and off.]

    Don't forget to click "Mark as Answer" on the post that helped you.
    This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
  • Re: Login control FAQ :

    05-23-2009, 4:00 AM
    • All-Star
      36,899 point All-Star
    • rtpHarry
    • Member since 10-01-2006, 12:51 PM
    • Lincoln, England
    • Posts 5,953

    TATWORTH:

     Anas

      Excellent article! Is there a way of switching a site based upon a database setting so that only administrators can access a given site?

    [Edit: I suppose that if accounts can be programmatically diabled and re-enabled, I could just switch the non-admin accounts on and off.]

     

    I didnt get what you were saying at all last night... not sure I do now hehe, do you mean a lock down mode that would shut out all normal users?

  • Re: Login control FAQ :

    05-23-2009, 5:37 PM
    • All-Star
      63,185 point All-Star
    • TATWORTH
    • Member since 02-04-2003, 1:34 PM
    • England
    • Posts 12,333
    • TrustedFriends-MVPs

    rtpHarry:
    I didnt get what you were saying at all last night... not sure I do now hehe, do you mean a lock down mode that would shut out all normal users?
     

    I need to be able to block non-admins from using the site by an administrator making a change within the database and not by changing the web.config in the users folder. Conversely when the lock-out period is over, the administrator needs to be be able to allow normal user access to resume just by means of an administrator option. The site administrators are quite non-technical and hence changing any of the sub-directory web.configs is not an option.

    Don't forget to click "Mark as Answer" on the post that helped you.
    This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
  • Re: Login control FAQ :

    05-24-2009, 12:02 AM
    • All-Star
      60,921 point All-Star
    • anas
    • Member since 09-21-2006, 8:31 AM
    • Palestinian Territory, Occupied
    • Posts 6,865
    • Moderator

    Hi Mr TATWORTH,

    TATWORTH:
    I need to be able to block non-admins from using the site by an administrator making a change within the database and not by changing the web.config in the users folde

    One solution is to  Handle the AuthenticateRequst event in global.asax file and check the user role :

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            // if the current requested url is not the login page 
            // and if someFlagInDatabase is true  
            if (!IsLoginPage && someFlagInDatabase == true)
                if (! Roles.IsUserInRole("Administrators"))
                {
                    Context.RewritePath("~/SiteIsCurrentlyUnAvailable.asxp");
                }
        }
        
        protected string LoginUrl
        {
            get { return "~/Login.aspx"; }
        }
    
        // return true if the current page is the Login Page .
        private bool IsLoginPage
        {
            get
            {
                return VirtualPathUtility.GetFileName(Request.Path).ToLower() ==
                    VirtualPathUtility.GetFileName(LoginUrl.ToLower());
            }
        }

    Where "someFlagInDatabase" is the value that decide whether the site will be available just for admins.

    Regards,

    Anas Ghanem | Blog

  • Re: Login control FAQ :

    05-24-2009, 4:15 AM
    • All-Star
      63,185 point All-Star
    • TATWORTH
    • Member since 02-04-2003, 1:34 PM
    • England
    • Posts 12,333
    • TrustedFriends-MVPs

     Anas

       Thank you for your excellent suggestion. I will try it at my client's site.

    Don't forget to click "Mark as Answer" on the post that helped you.
    This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
  • Re: Login control FAQ :

    05-26-2009, 8:37 AM
    • Member
      52 point Member
    • swapnal
    • Member since 08-10-2008, 12:04 PM
    • Posts 18

    Hi

    Nice post.

    need one more piece of information, How to achive single sign on using form authentication?

    Thank you

    Regards
    swapnal R. chonkar

  • Re: Login control FAQ :

    06-25-2009, 10:08 AM
    • All-Star
      63,185 point All-Star
    • TATWORTH
    • Member since 02-04-2003, 1:34 PM
    • England
    • Posts 12,333
    • TrustedFriends-MVPs

    Does the ASPNET membership provide any facility for a user to update their email address or does it require directly updating the Email and  LoweredEmail columns in aspnet_Membership by custom stored procedures and code?
     
        

    Don't forget to click "Mark as Answer" on the post that helped you.
    This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
  • Re: Login control FAQ :

    06-25-2009, 10:42 AM
    • All-Star
      60,921 point All-Star
    • anas
    • Member since 09-21-2006, 8:31 AM
    • Palestinian Territory, Occupied
    • Posts 6,865
    • Moderator

    Hi ,

    You can use Membership.UpdateUser method to update the user information:

            MembershipUser muser = Membership.GetUser("UserName here");
            muser.Email = " the new email here";
            Membership.UpdateUser(muser);


    Regards,

    Anas Ghanem | Blog

  • Re: Login control FAQ :

    06-25-2009, 4:55 PM
    • All-Star
      36,899 point All-Star
    • rtpHarry
    • Member since 10-01-2006, 12:51 PM
    • Lincoln, England
    • Posts 5,953

    swapnal:

    Hi

    Nice post.

    need one more piece of information, How to achive single sign on using form authentication?

    Thank you

    Regards
    swapnal R. chonkar

    There are several ways to solve this and it changes depending onyour exact setup.

    Searching for "asp.net single sign on" will show you lots of introductory tutorials that outline the concept.

    This tutorial will teach you the remaining details that you need to get any combination of SSO working:

Page 1 of 2 (24 items) 1 2 Next >