Here I included the column 'Roles' in tblUsers table itself.
Step2: Now we need a method using which we can get the roles from database, probably ',' separated or a string array of roles. We can write this method in a class, which is placed in App_Code folder (for say UserInfo.cs).
public static string[] GetRoles(string un)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["csMSNET"].ToString();
try
{
con.Open();
string sql = "select roles from tblUsers where UserName = '" + un + "'";
SqlCommand cmd = new SqlCommand(sql, con);
string strRoles = cmd.ExecuteScalar().ToString();
return strRoles.Split(',');
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
}
Note: Here I am getting the connection string from web.config, which is named 'csMSNET'.
Step3: This is an important step, as we are going to attach the roles to the given user.
User.Identity.Name gives us username and once we have roles, we have to change the user which is there in the current context, so that it includes both username as well as roles.
The right place to attach roles to the user is Application_AuthenticateRequest event in Global.asax.
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
string[] arRoles = UserInfo.GetRoles(User.Identity.Name);
Context.User = new System.Security.Principal.GenericPrincipal(User.Identity, arRoles);
}
}
Note: Before getting the roles and attaching them to the user, first you need to ensure that the user is authenticated or not.
Step4: Now user has identity and roles, both. Now based on roles deny or allow access.
ex: Deny access to all anonymous users and also users with r1 or r3 roles.
<authorization>
<deny users="?"/>
<deny roles ="r1, r3"/>
</authorization>
We can programmatically find out if a given user has some role or not using IsInRole method of Page.User
Ex:
User.IsInRole("r1")
Conclusion: Generally what we do is based on the role, we will hide certain items on the page. If the user is administrator, I would provide a facility to add and delete, but if the user is some report generator, I would just give the facility of view, no add or delete.
So, we need to set the visible property to false, in that way we use User.IsInRole to know the given user is in the specified role or not.
No comments:
Post a Comment