ASP.NET Authentication

I have the following a login page where the user enters in their username and password.

With that info, I need to then make sure that they are part of the Admin1 role If so, I like to set a cookie on the user’s machine.

With the code I have below User.InRole it doesn’t enter into the if statement. If I uncomment the FormsAuthentication.SetAuthCookie(txtUserName.Text, true); above it works.
Meaning shouldn’t I set the cookie only if the user is part of Admin1 role

I have the following but does not seem to work:

    if (Membership.ValidateUser(txtUserName.Text, txtPassword.Text))
    {

     //   FormsAuthentication.SetAuthCookie(txtUserName.Text, true);

        if (User.IsInRole("Admin1"))
        {
            // code never reaches here 
            FormsAuthentication.SetAuthCookie(txtUserName.Text, true);

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

User.IsInRole("Admin1") is false right after validation, because principal object hasn’t been attached to the current HttpContext yet.

If you really want to use Context.User, you need to manually attach principal object.

var username = txtUserName.Text;
var password = txtPassword.Text;

if (Membership.ValidateUser(username , password))
{
    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

    // Basically User.IsInRole("Admin1") is same as roles.Contains("Admin1")
    if (User.IsInRole("Admin1"))
    {
        FormsAuthentication.SetAuthCookie(username, true);
    }
}

Updated – Authenticate user using Login Control

Since you are using Membership Provider and Role Provider, I would like to suggest to use Login Control.

Once user is authenticated, you can use LoggedIn event to redirect user to appropiate page.

<asp:Login ID="LoginUser" runat="server" EnableViewState="false" 
   RenderOuterTable="false" OnLoggedIn="LoginUser_LoggedIn">
   ...
</asp:Login>

protected void LoginUser_LoggedIn(object sender, EventArgs e)
{
   // Now we know that user is authenticated
   // Membership user = Membership.GetUser(Login1.Username);
   var roles = Roles.GetRolesForUser(Login1.Username);

   if(roles.Contains("Admin1"))
      Response.Redirect("~/Admin/");
   else
      Response.Redirect("~/Users/");       
}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply