Contents tagged with membership

  • Membership in ASP.Net applications - part 4

    This is the fourth post in a series of posts regarding ASP.Net built in membership functionality,providers,controls. You can read the first one  here .You can read the second post here . You can read the third post here.

    In this post I will show you how to add users programmatically to a role. In the third post we saw how to get users in a specific role.I will also show you how to delete a user and a role programmatically.

    1) Launch Visual Studio 2005,2008/2010. Express editions will work fine. I am using Visual Studio 2010 Ultimate edition.

    2) Create an empty asp.net web site. Choose an appropriate name. 

    3) Add an item to your website, a web form. Leave the default name.

    4) Now go to the Visual Studio menu and choose Website->ASP.NET configuration

    You will see a new web page loading. Refresh your solution in the Solution Explorerwindow. You will see the App_Data special folder added to your solution and inside the special folder you will see the ASPNETDB.MDF database.This is a SQL database.

    5) Go back to your web configuration web page that was loaded when we clicked theWebsite->ASP.NET configuration.Choose Forms Authetication

    6) Choose Security and enable roles. When you do that you will see changes in theweb.config file. A new line will be added.
    <roleManager enabled="true" />
    7)  Add a new role called e.g "friends".Now we must add some users to these roles.In the security tab (in the web environment), click "Create user". All this data is saved into the ASPNETDB.MDF database.

    I created a new user and added him to the friends role. Make sure you use a strong password with 7 characters or more containing at least one non-alphanumeric character.

     

    8) Create 2-3 more roles and 3-4 users and add them to those roles through the WAT(Web administration tool)

     

    9) Add a label,2 dropdown list,a bulleted list and a button control on the form.

     

    We will get the users and the roles we have so far and bind them to the dropdown list controls. In the Page_Load event handling routine type,

     

    if (!Page.IsPostBack)

    {

    DropDownList1.DataSource =
    Roles.GetAllRoles();

    DropDownList1.DataBind();

    DropDownList2.DataSource =
    Membership.GetAllUsers();

    DropDownList2.DataBind();

    }

     

    This is very easy code to follow.

     

    10) In the bulleted list control we will bind the users in the specific role when the user selects the role from the first dropdown list.

     

     protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)

    {

    BulletedList1.DataSource =
    Roles.GetUsersInRole(DropDownList1.SelectedItem.Text.ToString());

    BulletedList1.DataBind();

    }

     

    11) Now we need to select the role from the first dropdownlist control and the user from the second dropdownlist control.

     

    The user in the second dropdownlist control should not be a member of the role in the first dropdownlist control.

     

    In the Button1_Click() event handling routine type,

     

    try

    {

    Roles.AddUserToRole(DropDownList2.SelectedItem.Text.ToString(), DropDownList1.SelectedItem.Text.ToString());BulletedList1.DataSource = Roles.GetUsersInRole(DropDownList1.SelectedItem.Text.ToString());

    BulletedList1.DataBind();

    Label1.Text = "<em>" + DropDownList2.SelectedItem.Text.ToString() + "</em>" +

    " has been added to the " +

    "<em>" + DropDownList1.SelectedItem.Text.ToString() + "</em>" +

    " role";

    }

    catch (Exception ex)

    {

    Response.Write(ex.Message);

    }

     

     

    12) Run your application and select any role you want. All the users of the specified role will appear. Now select a role and a user that does not belong to the role. Hit the button. That user will be added to the role.

     

    13) Now we will see how to delete a user and a role using the Membership and Roles static classes.

     

    14) Add a new item to your site, a web form. Name it DeleteUser.aspx.

     

    Add a button, a label, a dropdowlist control on the form.

     

    15) We will create a void method to get all existing users.

     

    private void GetExistingUsers()

    {

    DropDownList1.DataSource =
    Membership.GetAllUsers();

    DropDownList1.DataBind();

    }

     

    In the Page_Load event handling routine type,

     

      if (!Page.IsPostBack)
            {

                GetExistingUsers();
            }

     

    16) In the Button1_Click() event handling routine type,

     

    try

    {

    Membership.DeleteUser(DropDownList1.SelectedItem.Text);

    Label1.Text = "<em>" + DropDownList1.SelectedItem.Text.ToString() + "</em>" +

    " has been deleted";

    GetExistingUsers();

    }

    catch (Exception ex)

    {

    Label1.Text = ex.Message;

    }

     

    I am using the DeleteUser method to delete the user.

     

    Run your application and select a user from the dropdownlist control. Hit the button. The selected user will be deleted.

     

    17) Let's do something very similar when deleting the role. Add a new item to your site, a web form. Name it DeleteRole.aspx

    I know we repeat some code in these posts but I think it will be of great benefit to people to type a few times the code.

     

    Add a button, a label, a dropdowlist control on the form.

     

    15) We will create a void method to get all existing users.

     

    private void GetExistingRoles()

    {

    DropDownList1.DataSource = Roles
    .GetAllRoles();

    DropDownList1.DataBind();

    }

     

    In the Page_Load event handling routine type,

     

      if (!Page.IsPostBack)
            {

                GetExistingRoles();
            }

     

    16) In the Button1_Click() event handling routine type,

     

    try

    {

    string[] myusers = Roles.GetUsersInRole(DropDownList1.SelectedItem.Text);

    int length = myusers.Length;

    if (length == 0)

    {

    Roles.DeleteRole(DropDownList1.SelectedItem.Text);

    Label1.Text = "<em>" + DropDownList1.SelectedItem.Text.ToString() + "</em>" +

    " has been deleted";

    GetExistingRoles();

    }

    else

    Label1.Text = "you cannot delete a role that has existing users attached to it";

    }

    catch (Exception ex)

    {

    Label1.Text = ex.Message;

    }

     

    I am using the DeleteRole method to delete the role.Before that I must check to see if there are any users under the role.

     

    Run your application and select a role from the dropdownlist control. Hit the button. The selected role will be deleted,unless it has users.

     

    Hope it helps!!!

    Read more...

  • Membership in ASP.Net applications - part 3

    This is the third post in a series of posts regarding ASP.Net built in membership functionality,providers,controls. You can read the first one post one here .

    You can read the second post here. In this post I would like to investigate how to use the Membership class methods to achieve the same functionality we have with the login web server controls.The login web server controls live inside the .aspx pages and access the underlying abstract membership classes to perform the desired functionality. We can access them directly when we do not want to have our users logged in/authenticated through the Login web server control.Some people will say that there is no point to do that. Well, we might want to implement some sort of bussiness logic when the user is validated.

    1) Launch Visual Studio 2005,2008/2010. Express editions will work fine. I am using Visual Studio 2010 Ultimate edition.

    2) Create an empty asp.net web site. Choose an appropriate name. 

    3) Add an item to your website, a web form. Leave the default name.

    4) Now go to the Visual Studio menu and choose Website->ASP.NET configuration

    You will see a new web page loading. Refresh your solution in the Solution Explorerwindow. You will see the App_Data special folder added to your solution and inside the special folder you will see the ASPNETDB.MDF database.This is a SQL database.

    5) Go back to your web configuration web page that was loaded when we clicked the Website->ASP.NET configuration.Choose Forms Authetication

    6) Choose Security and enable roles. When you do that you will see changes in the web.config file. A new line will be added.
    <roleManager enabled="true" />
    7)  Add a new role called e.g "friends".Now we must add some users to these roles.In the security tab (in the web environment), click "Create user". All this data is saved into the ASPNETDB.MDF database.

    I created a new user and added him to the friends role. Make sure you use a strong password with 7 characters or more containing at least one non-alphanumeric character.

    8) In the Default.aspx page I am going to use the LoginView control and the LoginStatus control.There are 2 templates,AnonymousTemplate and LoggedInTemplate. I place a LoginStatus control in the AnonymousTemplate.I place a LoginStatus control and the same LoginNamecontrol I had before in the  LoggedInTemplate.

    <asp:LoginView runat="server">

    <AnonymousTemplate>

    you are not logged in .

    <br />

    <asp:LoginStatus ID="LoginStatus1" runat="server" />

    </AnonymousTemplate>

    <LoggedInTemplate>

    You are logged in, <asp:LoginName ID="LoginName1" runat="server" /><br />

    <asp:LoginStatus ID="LoginStatus1" runat="server" />

    </LoggedInTemplate>

    </asp:LoginView>

    9) So far we have the same steps as in the previous steps. Now we will add another web form to the site and name it Login.aspx.

    We will not use the Login control.

    We will add 2 textboxes, a button and a label on the Login.aspx. The markup looks like this

    <form id="form1" runat="server">

    <div>

    Username<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />

    Password<asp:TextBox ID="TextBox2"

    runat="server" TextMode="Password"></asp:TextBox>

    </div>

    <p>

    <asp:Button ID="Button1" runat="server" Text="Log in" Height="26px"

    onclick="Button1_Click" />

    </p>

    <asp:Label ID="Label1" runat="server" Text="Failed!!!!" Font-Bold="true" Visible="False"></asp:Label>

    </form>

    10) In the Button1_Click event handler routine type

      if (Membership.ValidateUser(TextBox1.Text, TextBox2.Text))
            {
               
                FormsAuthentication.RedirectFromLoginPage(TextBox1.Text,false);
            }
         

          Label1.Visible=true;

    I use the ValidateUser() method to verify that the supplied username and password are valid.Then redirect the authenticated user to the originally requested page.

    Run your application and try to log in. Try first with the correct username and password. Then try with the wrong username or password.

    11) Now we will add a new page to our site.I name it GetRoles.aspx. We will get the roles that already exist and add a new role.

    12) We add a bulleted list control, a textbox control,a label control and a button control.The markup for the GetRoles.aspx looks like this.

    <form id="form1" runat="server">

    <div>

    <asp:BulletedList ID="BulletedList1" runat="server">

    </asp:BulletedList>

    </div>

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

    <p>

    <asp:Button ID="Button1" runat="server" onclick="Button1_Click"

    Text="Create a new role" />

    </p>

    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

    </form>

     

    13) We create a simple void method to show the existing roles. We call this method from the Page_Load event handling routine.

    The method looks like this

    private void ShowRoles()

    {

    BulletedList1.DataSource =
    Roles.GetAllRoles();

    BulletedList1.DataBind();

    }

    In the Page_Load event handling routine we just call the method

    protected void Page_Load(object sender, EventArgs e)

    {

     if (!IsPostBack)
     
            
            ShowRoles();

    }

    Run the application and see the role(s) you created earlier.

    14) In the Button1_Click() event handling routine type,

    if (Roles.RoleExists(TextBox1.Text) == false)

    {

    Roles.CreateRole(TextBox1.Text);

    Label1.Text = TextBox1.Text +

    " :New role added";

    ShowRoles();

    }

    else

    {

    Label1.Text = TextBox1.Text +

    "You cannot add this role because it exists in our database";

    }

    Basically I am just using the various methods(RoleExists,CreateRole,GetAllRoles) of the Roles static class.

    Run the application,create a new role and see the new role added.

    15) Now we will add a new web form to the site and we will try to get the users that belong to a specified role.Name the new form UsersInRole.aspx

    16) We will add a button, a dropdownlist and bulletedlist control

    <form id="form1" runat="server">

    <div>

    </div>

    <asp:DropDownList ID="DropDownList1" runat="server">

    </asp:DropDownList>

    <p>

    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

    </p>

    <asp:BulletedList ID="BulletedList1" runat="server">

    </asp:BulletedList>

    </form>

    17) We will have a method that gets all the roles and bind them to the dropdownlist control.

    private void ShowRoles()

    {

    DropDownList1.DataSource =
    Roles.GetAllRoles();

    DropDownList1.DataBind();

    }

    In the Page_Load event handling routine we just call the method

    protected void Page_Load(object sender, EventArgs e)

    {

    ShowRoles();

    }

    18) In the Button1_Click() event handling routine type, BulletedList1.DataSource=Roles.GetUsersInRole(DropDownList1.SelectedItem.Text.

    ToString());

    BulletedList1.DataBind();

     

    Run your application and select from the dropdown list the role and click the button to see the users in that role.

    Hope it helps!!!

    Read more...

  • Membership in ASP.Net applications - part 1

    So far in all my posts, I have never mentioned anything about how to implement authentication/authorisation mechanisms in a web site.  In all our professional web applications we do need some sort of mechanism to verify who users are and what privileges have in our site. 

    This is the first post in a series of posts investigating how to implement membership (authentication+authorisation) in ASP.Net applications.

    We will look into the built-in web server security controls.We will look at the built-in providers and the provider architecture.

    The membership and role providers were introduced in ASP.Net 2.0. Through that we can have role management,login functionality and many features out of the box like (password complexity,forgot your password,security question,password reset).

    So if you are looking for a RAD solution when it comes to membership you can use the out of the box membership model that ships out of the box since ASP.Net 2.0. The default membership and login controls are not ideal for any situation. It depends on the authentication/authorisation requirements of your application.

    I will start by showing you how to use the standard controls for a RAD of a membership web site.

    We will use a hands on example to demonstrate that, as always.Bear in mind this is a beginner level post.

    1) Launch Visual Studio 2005,2008/2010. Express editions will work fine. I am using Visual Studio 2010 Ultimate edition.

    2) Create an empty asp.net web site. Choose an appropriate name.

    3) Add an item to your website, a web form. Leave the default name.

    4) Add the following markup in the default.aspx page (inside the form element)

     You are 
            <asp:LoginName ID="myLoginName" runat="server" BackColor="Silver" 
                BorderColor="#CC3300" Font-Bold="True" ForeColor="Blue" />.
        Welcome to our home page!!!

     

     5) Now we have to make some changes to our rather (empty) web.config file.We want to have Forms authentication and deny all anonymous requests.Add the following lines in the configuration file.

     <authentication mode="Forms"></authentication>
          <authorization>
            <deny users="?"/>
          </authorization>

     

    At this point it is important to highight these

    • Default authentication is set to Windows
    • Default authorisation is set to allow anomymoys access. 

    6) Now we have to add another item in our website, another web form. This is going to be our Login page. Name it Login.aspx page. Drag and drop the Login web server control on the form.In my case the markup looks like this

       <asp:Login runat="server" BackColor="#E3EAEB" BorderColor="#E6E2D8" 
       BorderPadding="4" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" 
       Font-Size="0.8em" ForeColor="#333333" TextLayout="TextOnTop">
       <InstructionTextStyle Font-Italic="True" ForeColor="Black" />
       <LoginButtonStyle BackColor="White" BorderColor="#C5BBAF" BorderStyle="Solid" 
       BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#1C5E55" />
       <TextBoxStyle Font-Size="0.8em" />
       <TitleTextStyle BackColor="#1C5E55" Font-Bold="True" Font-Size="0.9em" 
       ForeColor="White" />
       </asp:Login>

    7) Now go to the Visual Studio menu and choose Website->ASP.NET configuration

    You will see a new web page loading. Refresh your solution in the Solution Explorer window. You will see the App_Data special folder added to your solution and inside the special folder you will see the ASPNETDB.MDF database.This is a SQL database.

    8) Go back to your web configuration web page that was loaded when we clicked the Website->ASP.NET configuration.

    Choose Security and enable roles. When you do that you will see changes in the web.config file. A new line will be added.

    <roleManager enabled="true" />
    9) Go back to the security page and add 2 new roles. I added "friends" and "Manager" as my two roles. 

    10) Now we must add some users to these roles.In the security tab (in the web environment), click "Create user". All this data is saved into the ASPNETDB.MDF database.

    I created a new user and added him to the friends role. Make sure you use a strong password with 7 characters or more containing at least one non-alphanumeric character.

    11)  We will create another user and add him to the Manager role.

    12)  Launch your site. You will see that instead of seeing the Default.aspx page you will be redirected to the Login.aspx page.Remember we do not want any anonymous requests. We have an authentication system set up with no code.That is pretty impressive.

    13) Try to login to your site using the credentials of the user that you have just created.As soon as we do that we are redirected to the Default.aspx page and our username is displayed to the page. In my case it displays

    "You are nikolaosk. Welcome to our home page!!!" 

    So we write no code and we have great functionality. When someone types some credentials in the Login control, the OnAuthenticate method is called.

    Then inside that method a call to the ValidateUser() method is made and under the hood a stored procedure is called (takes 2 paramaters : username,password) and that is how you are validated. The stored procedure and the tables are inside the ASPNETDB.MDF database. I urge you to have a look at the schema and data-objects of the ASPNETDB.MDF database.

    Basically a call is made to the current membership provider. The default provider is "AspNetSqlMembershipProvider".

    That is set up from the machine.config file. We can change that if we want by specifying another provider in our web.config file.

    14)  The way it works is like this.In the .aspx pages we add security controls or type our own custom code. These security controls know how to talk to the membership/role abstract classes.

    Inside the web.config file we can select the authetication,authorisation settings and other things like the provider (SQL provider e.t.c). You can write your own provider.

    I will continue with more posts on membership in ASP.Net.Stay tuned.

    Hope it helps!!!

     

     

    Read more...