Tuesday, December 16, 2008

Security in ASP.NET

In every web based application, the main concern that should be taken care from the very beginning is security. Although we have https which is secure but all before that there is a need to have security checks at the time when user submits the information.
Here I will not talk about the Forms Authentication as I consider the reader to be aware about it but its better to study it before going any further. You can learn about Forms Authentication in www.4guysfromrolla.com/webtech/110701-1.shtml.
Let start with Membership & Role Manager. Basically it has two classes ie Membership & MembershipUser. Some common tasks performed by Membership class are as follows:-
  • Creating a new MembershipUser
  • Validating a username-password combination when a user attempts to log in
  • Retrieving MembershipUser instance
  • Updating MembershipUser instance
  • Searching for users
  • Getting the count of authenticated users that are currently online
  • Deleting users from the system when they are no longer needed
Now lets see what is Role Manager. The Roles provides methods for creating roles and assigning users to roles. Some common tasks performed by roles are:-
  • Creating a new role
  • Deleting an existing role
  • Assigning users to roles
  • Removing users from roles
  • Determining if a user is authorized to a specific role
  • Searching for users in a specific role, as well as retrieving all users in a role
  • Getting the role information for a specific user
Following is a step by step code snippet in implementing membership & assigning Roles:-
  1. Create User: On button click write this code

        string userName = txtUserId.Text;


    string password = txtPassword.Text;

    string email = txtEmail.Text;
    string passwordQuestion = ddlPasswordQuestion.SelectedValue;


    string passwordAnswer = txtPasswordAnswer.Text;

    MembershipCreateStatus result;
    Membership.CreateUser(userName, password, email, passwordQuestion, passwordAnswer, true,out result);
  2. User Login: 
    On page Load write this code
    private MembershipUser memUser;
    memUser = Membership.GetUser();

    On Logout button write this code:
    FormsAuthentication.SignOut();
    Roles.DeleteCookie();
  3. Manage Roles: On button click of create role write this,
    string roleName = txtCreateRole.Text;

    Roles.CreateRole(roleName);
  4. Manage User and Roles: Write this code on button click

    Roles.AddUserToRole(User.Identity.Name, selectedRole);
  5. Check Authorization: Write this code on page load
    if(User.IsInRole("Administrator")
    {
    }
    else
    {
    Response.Write("Invalid User");
    }
This is just an overview how Membership and Roles can be managed for security in ASP.NET
For complete code with working example, you can contact me at sameersayani@gmail.com


0 comments: