Understanding ASP.NET Page Life Cycle and Role-Based Authorization

365 views Asked by At

What I am trying to do

Authenticate a user, and redirect them to a page based on their role.

My issue

The first time entering correct credentials it fails. The user is authenticated, but when evaluating what role they are in, none of the if statements are true. The second time (after a post-back) it works as expected.

My question

Why does this not work; why do I have to authenticate a user, and post-back before the roles are set?

Code

Private Sub Login1_Authenticate(sender As Object, e As AuthenticateEventArgs) Handles Login1.Authenticate
If Membership.ValidateUser(Login1.UserName, Login1.Password) Then
  FormsAuthentication.SetAuthCookie(Login1.UserName, False)
  ToPage()
End If
End Sub

Private Sub ToPage()
If User.IsInRole("Role1") Then
  Response.Redirect("~/Page1.aspx")
End If

If User.IsInRole("Role2") Then
  Response.Redirect("~/Page2.aspx")
End If

If User.IsInRole("Role3") Then
  Response.Redirect("~/Page3.aspx")
End If
End Sub
1

There are 1 answers

0
Jignesh Suvariya On BEST ANSWER

Use following it is in c# convert into VB

if (Membership.ValidateUser(username , password))
{
    FormsAuthentication.SetAuthCookie(username, true);

    var roles = Roles.GetRolesForUser(username);
    var identity = new GenericIdentity(username);
    var principal = new GenericPrincipal(identity, roles);
    Context.User = principal;

    // Now you can use Context.User

    if (User.IsInRole("Role1"))
    {
        Response.Redirect("~/Page1.aspx")
    }
    else if(User.IsInRole("Role2"))
    {
        Response.Redirect("~/Page2.aspx")
    }
    else
    {
        Response.Redirect("~/default.aspx")
    }
}

you can also use following

if (Membership.ValidateUser(username , password))
{
   FormsAuthentication.SetAuthCookie(username, true);

   var roles = Roles.GetRolesForUser(username );

   if(roles.Contains("Role1"))
      Response.Redirect("~/Page1.aspx");
   else if(roles.Contains("Role2")) // check for other roles
      Response.Redirect("~/Page2.aspx");
   else
      Response.Redirect("~/default.aspx"); 
}