Another way to do user based security
This is in response to a post by Anas Ghanem – regarding doing Session checks in Page Loads, and asks for a better way to do things – in my opinion there is.
Instead of doing:
public class AdminSecuredPage : System.Web.UI.Page
{
public AdminSecuredPage()
{}
protected override void OnInit(EventArgs e)
{
// if the user is not Admin , redirect to Login Page
if (Session["AdminUser"] == null)
Response.Redirect("~/login.aspx");
// this needed to initialize its base page class
base.OnInit(e);
}
}
You really should be doing:
But, you can further extend this by inherting from a parent base page, like so:
public class BasePage : System.Web.UI.Page { public void RequireRole (String Role) { if (!User.IsInRole(Role)) { Response.Redirect("~/Login.aspx"); } } public void RequireAdministrator() { RequireRole("Administrator"); } }
And then you do the following in the page:
public partial class _Default : BasePage { protected void Page_Load(object sender, EventArgs e) { RequireRole("Administrator"); // OR RequireAdministrator(); } }
I think this is a much more elegant way of doing things, plus you are DRY compatible, since you only have to change one url to redirect to.


Thanks for the Post,Actually I know that the FormsAuthentication is better than the session ! no one want to “re-invent the wheel !” , Actually I was talking about How to Avoid using the session in page constructor, and I liked to know if there is a workaround for using the session in the page constructor , like some methods which can be called to force the runtime to populate the session in early stage so that it will be available at the time the constructor is called …
Any way , thank you very much for the nice blog .
Best Regards,
Anas Ghanem
8 May 08 at 9:43 pm